我有一个包含以下内容的示例表
工作表1
User Name Age
工作表2
User Name Age
如果用户与用户相同,我想从 Worksheet2 中删除该行。 strong>工作表1
我编写了以下VBA程序,但始终出现需要对象错误,我不知道为什么会这样
Sub columnCompare()
Dim sh1 As Worksheet, sh2 As Worksheet, r1 As Range, r2 As Range
Set sh1 = Worksheets("Users SBC")
Set sh2 = Worksheets("Users JDF")
Set r1 = sh1.Range("A2")
Set r2 = sh2.Range("A2")
While r1 <> ""
Set r2 = sh2.Range("A2")
While r2 <> ""
Set r2 = r2.Offset(1, 0)
If r1 = r2 Then r2.EntireRow.Delete
Wend
Set r1 = r1.Offset(1, 0)
Wend
End Sub
答案 0 :(得分:2)
我对您的代码进行了一些更改。正如我在评论中所说,删除您r2
所在的行将清除它。
Sub columnCompare()
Dim sh1 As Worksheet, sh2 As Worksheet, r1 As Range, r2 As Range, i As Integer
Set sh1 = Worksheets("XX")
Set sh2 = Worksheets("YY")
Set r1 = sh1.Range("A2")
Set r2 = sh2.Range("A2")
While r1 <> ""
Set r2 = sh2.Range("A2")
While r2 <> ""
If r1 = r2 Then r2.Value = "delete"
Set r2 = r2.Offset(1, 0)
Wend
Set r1 = r1.Offset(1, 0)
Wend
For i = r2.Row To 2 Step -1
If sh2.Range("A" & i).Value = "delete" Then sh2.Rows(i).EntireRow.Delete
Next i
End Sub
答案 1 :(得分:0)
另一种方法是先进行偏移,然后删除前一行(具有负偏移)。在另一个答案的结尾将您保存为循环。
While r1 <> ""
Set r2 = sh2.Range("A2")
While r2 <> ""
If r1 = r2 Then
Set r2 = r2.Offset(1, 0)
r2.Offset(-1, 0).EntireRow.Delete
Else
Set r2 = r2.Offset(1, 0)
End If
Wend
Set r1 = r1.Offset(1, 0)
Wend