在我的名为“数据”的表格中,我有大约200行。 A列有一个ID号,其余列只是数据。 在我在A栏中名为“检查”的另一张表中,我也有ID号列表。 我想要的是删除我的数据表中具有我的检查表中的客户ID的所有行。
所以我的思考过程就是如果我做一个vlookup并返回一个值然后删除该行,否则移动到下一个 由于某种原因,这只是删除所有行。
Sub EraseDups()
Dim N As Long, i As Long
N = Cells(Rows.Count, "A").End(xlUp).Row
For i = N To 1 Step -1
If Application.WorksheetFunction.VLookup(Cells(i, "A"), Sheet1.Range("A:A"), 1, False) > 1 Then
Cells(i, "A").EntireRow.Delete
End If
Next i
End Sub
答案 0 :(得分:1)
另一种方法......
使用Countif,而不是使用Vlookup或Match,这不会产生错误,因此不需要进行错误处理。
Sub EraseDups()
Dim wsData As Worksheet, wsCheck As Worksheet
Dim N As Long, i As Long
Application.ScreenUpdating = False
Set wsData = Sheets("Data")
Set wsCheck = Sheets("Check")
With wsData 'Change this to the specific sheet if wanted
N = .Cells(Rows.Count, "A").End(xlUp).Row
For i = N To 1 Step -1
If Application.CountIf(wsCheck.Range("A:A"), .Cells(i, "A")) > 0 Then
.Rows(i).Delete
End If
Next i
End With
Application.ScreenUpdating = True
End Sub
答案 1 :(得分:0)
问题是如果vlookup返回错误,它将停止代码。我们需要从代码中提取,然后检查错误:
Sub EraseDups()
Dim N As Long, i As Long, j as Long
With ActiveSheet 'Change this to the specific sheet if wanted
N = .Cells(Rows.Count, "A").End(xlUp).Row
For i = N To 1 Step -1
j = 0
On Error Resume Next
j = Application.WorksheetFunction.Match(.Cells(i, "A"), Sheet1.Range("A:A"), 0)
On Error Goto 0
If j > 0 Then
.Rows(i).Delete
End If
Next i
End With
End Sub