Code not looping through sheets

2019-09-17 23:02发布

The following code is deleting too much on first sheet and then not looping to second sheet?? Error appearing on .FindNext statement.

Sub FindAndExecute3()
Dim Loc As Range
Dim sh As Worksheet
For Each sh In ThisWorkbook.Worksheets
    With sh.UsedRange
        Set Loc = .Cells.Find(What:="AUTO.WHSE.")
        If Not Loc Is Nothing Then
          Do Until Loc Is Nothing
            Rows(ActiveCell.Row & ":" & (ActiveCell.Row + 2)).Delete
            Set Loc = .FindNext(Loc)
          Loop
        End If
    End With
    Set Loc = Nothing
Next
End Sub

1条回答
小情绪 Triste *
2楼-- · 2019-09-17 23:36

You have to fully qualify your Ranges. This issue shows up once and again (e.g., this).

What does this mean? Do not use Cells, Range, Rows or Columns without specifying which Worksheet they belong to, unless you specifically want to do that (and even in that case, explicitly using ActiveSheet improves readability and reduces the chances of errors, similar to using Option Explicit). For instance, replace

Rows(ActiveCell.Row & ":" & (ActiveCell.Row + 2)).Delete

with

sh.Rows(sh.<something>.Row & ":" & (sh.<something>.Row + 2)).Delete

I am assuming the Range to be deleted spans Row numbers taken from something related to sh.

Note 1: In this case, even without qualifying Ranges, code continues execution and the mistake may go unnoticed, as it produces a valid result. In other cases, code without fully qualified Ranges will throw an error (e.g., with something like sheet1.Range(Cells(..., when sheet1 is not the ActiveSheet).**

Note 2: You can work with the ActiveCell only when the Worksheet that it is on is the ActiveSheet [MSDN].

查看更多
登录 后发表回答