VBA错误:错误1004:错误对象_worksheet的方法范围失败

时间:2015-02-25 09:51:36

标签: vba

我正在尝试为此功能创建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 = " "

1 个答案:

答案 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