Excel VBA方法'范围'对象' _global'失败错误1004

时间:2017-05-10 20:11:55

标签: vba excel-vba excel

我无法解释为什么我会得到"' Range'对象' _global'失败"在我做的同时声明。就像名为RC3的范围未被识别一样。非常感谢任何帮助。

Sub DeleteBlankRows()

Dim Allrws As Range
Dim Rws As Range
Dim RC2 As Range
Dim RC3 As Range
Dim I As Integer
Dim CopyRange As Range
Dim LastRow As Long

With Application

'.ScreenUpdating = False ' don't spam the interface with selections

    With ActiveSheet

        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row ' Put the number of the last row in LastRow

    End With

    Set Allrws = Range("A2:S" & CStr(LastRow))  ' set range to be observed

    For Each Rws In Allrws.Rows   ' for each row in the range of Allrws call it Rws and do the following with it

        Set RC2 = Rws.Offset(0, 3).Resize(1, 1)      ' move and resize the range of RC2 to include only the cell under column D
        Set RC3 = Rws.Offset(0, 7).Resize(1, 1)      ' move and resize the range of RC3 to include only the cell under column I        
        I = 0   ' initilize the rows deleted counter

            Do While (Range(RC3).Value <> "" And I < 30)    ' as long as RC points to a empty cell and we haven't removed more then 30 rows keep removing rows                                                             

                If (range(RC2).Value = "Permit & Design" Or range(RC2).Value = "Miscellanious") Then 'don't delete row if Permit & Design or Miscellanious is in the cell under column D

                  I = 30        ' escape the loop if true

                Else

                  Selection.EntireRow.Delete      ' delete the selected row if false

                  I = I + 1                       ' add 1 to the counter

                End If        

            Loop                                   ' Go back to the start of the Do While

    Next Rws                    ' go back to the For Each and put the next row in Rws

    .ScreenUpdating = True      ' now update the interface with the changes

end with

end sub

1 个答案:

答案 0 :(得分:2)

Do While (Range(RC3).Value <> "" And I < 30)

RC3 is a Range objectRange(SomeRangeObject)的确是Range(SomeRangeObject.Value),所以除非RC3.Value包含有效的范围地址字符串,否则不合格的 Range调用将会爆炸。

注意不合格:您的代码隐式ActiveSheet下工作:

Set Allrws = Range("A2:S" & CStr(LastRow))

每当Range被使用时,它会通过ActiveSheet.Range隐藏模块隐式执行_Global

不合格的RangeCellsRowsColumnsNames来电都隐含地指ActiveSheet,以及误解这个事实是侧栏中每个“相关”问题背后的原因(我检查过的那些),并且在这个网站上还有数千个相同的问题:它是常见的bug来源。因此,限定工作表成员调用并避免出现问题。

您的代码发生工作(嗯,鉴于上述修改)。如果With ActiveSheet块已更改为With Sheet12,您将开始看到源自所有不合格的Range来电的问题。