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
You have to fully qualify your
Range
s. This issue shows up once and again (e.g., this).What does this mean? Do not use
Cells
,Range
,Rows
orColumns
without specifying whichWorksheet
they belong to, unless you specifically want to do that (and even in that case, explicitly usingActiveSheet
improves readability and reduces the chances of errors, similar to usingOption Explicit
). For instance, replacewith
I am assuming the
Range
to be deleted spansRow
numbers taken from something related tosh
.Note 1: In this case, even without qualifying
Range
s, code continues execution and the mistake may go unnoticed, as it produces a valid result. In other cases, code without fully qualifiedRange
s will throw an error (e.g., with something likesheet1.Range(Cells(...
, whensheet1
is not theActiveSheet
).**Note 2: You can work with the
ActiveCell
only when theWorksheet
that it is on is theActiveSheet
[MSDN].