我正在尝试为此功能创建VBA - 如果A列中的单元格包含“BG01”,则删除行。 A列的标题名称是“付款中心”
但是当我运行宏时,它会显示:对象_worksheet的错误方法范围
row_number = 1
Do
DoEvents
row_number = row_number + 1
Payment_Center = Sheet1.Range("A" & row_number) ' <~~~~~ Error occurs here
If InStr(Payment_Center, "BG01") >= 1 Then
Sheet1.Rows(row_number & ":" & row_number).Delete
row_number = row_number - 1
End If
Loop Until Payment_Center = " "
答案 0 :(得分:0)
发生错误是因为需要使用Set
关键字修改范围对象。
Set Payment_Center = Sheet1.Range("A" & row_number)
你的循环应该是
row_number = 1
Do
DoEvents
row_number = row_number + 1
Set Payment_Center = Sheet1.Range("A" & row_number) '
If InStr(Payment_Center, "BG01") >= 1 Then
Sheet1.Rows(row_number & ":" & row_number).Delete
row_number = row_number - 1
End If
' reset Payment_Center range using new row number
set Payment_Center = Sheet1.Range("A" & row_number)
Loop Until Payment_Center = " "
它应该有效
如果您在代码模块所有的顶部Option Explicit
,并且正确地声明所有变量,例如
Dim row_number As Integer
Dim Payment_Center as Range