gpt4 book ai didi

Excel VBA 对象在运行时需要错误

转载 作者:行者123 更新时间:2023-12-04 20:29:15 24 4
gpt4 key购买 nike

我对 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

提前致谢!

最佳答案

您可以遍历 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

关于Excel VBA 对象在运行时需要错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53106663/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com