Let me illustrate this with an example in Excel:
Say that you want to look at rows 2 through 100 of the active sheet, and delete a row if the cell in column C is empty and the cell in column D contains "Yes".
A first thought could be to write code like this:
Code: Select all
Dim r As Long
For r = 2 To 100
If Range("C" & r) = "" And Range("D" & r) = "Yes" Then
Range("C" & r).EntireRow.Delete
End If
Next r
The way around this is to loop backwards:
Code: Select all
Dim r As Long
For r = 100 To 2 Step -1
If Range("C" & r) = "" And Range("D" & r) = "Yes" Then
Range("C" & r).EntireRow.Delete
End If
Next r
A For Each loop always loops forwards, so it may suffer from the same problem. In the same situation as above, the following code will fail to delete row 18 too:
Code: Select all
Dim oCell As Range
For Each oCell In Range("C2:C100")
If oCell = "" And oCell.Offset(0, 1) = "Yes" Then
oCell.EntireRow.Delete
End If
Next oCell
Code: Select all
Dim n As Long
Dim oCell As Range
For n = Range("C2:C100").Cells.Count To 1 Step -1
Set oCell = Range("C2:C100").Cells(n)
If oCell = "" And oCell.Offset(0, 1) = "Yes" Then
oCell.EntireRow.Delete
End If
Next i
Thanks to Goshute for suggesting this subject!