我是VBA的新手,刚刚开始学习。我这里有一个代码来匹配Sheet1和Sheet3中“ M”列的所有单元格,并删除Sheet1中包含Sheet3的“ M”列中任何值的所有行。 如果使用F8进行操作,不会出现任何错误,但是当我将其分配给按钮时,它将在运行时失败,并显示“需要对象”错误。我尝试了一些在网上找到的东西,但似乎都没有用。 下面是我的代码。任何帮助将非常感激。
Sub DeleteRows()
Dim rng As Range
Dim rng2 As Range
Dim cell As Object
Dim cell2 As Object
Set rng = Sheets("Sheet1").Range("M2:M1541")
Set rng2 = Sheets("Sheet3").Range("M2:M30")
For Each cell In rng
For Each cell2 In rng2
If cell.Value = cell2.Value Then
cell.EntireRow.Delete
End If
Next
Next
Application.ScreenUpdating = True
End Sub
谢谢!
答案 0 :(得分:1)
您可以循环遍历sheet2中的单元格并为sheet1中的那些项过滤。 这样就不会出现双循环。
Sub Button1_Click()
Dim ws As Worksheet, sh As Worksheet
Dim LstRw As Long, Rng As Range, Frng As Range, c As Range, Nrng As Range
Set ws = Sheets("Sheet2")
Set sh = Sheets("Sheet1")
With ws
LstRw = .Cells(.Rows.Count, "M").End(xlUp).Row
Set Rng = .Range("M2:M" & LstRw)
End With
With sh
Set Frng = .Range("M2:M" & .Cells(.Rows.Count, "M").End(xlUp).Row)
For Each c In Rng.Cells
.Range("M1").AutoFilter Field:=1, Criteria1:=c
On Error Resume Next
Set Nrng = Frng.SpecialCells(xlVisible)
On Error GoTo 0
If Nrng Is Nothing Then
Else
Frng.EntireRow.Delete
End If
Next c
.AutoFilterMode = False
End With
End Sub