-1
Sub letr()

Dim i As Integer

For i = 3 To 25

    If Cells(i, 7) <> "CA" Then
    Rows(i).Delete
    End If

Next i

End Sub

The above code does not delete all the results(Total 4). i have to run the code twice to delete all the 4 results. Can anyone show me what i did wrong?

2
  • 2
    This is such a reoccuring problem. Run deletion from bottum-up or you simply not iterating all rows. To see this happening, step through your code using F8 and see results per step. Then again, best is to not delete one-by-one but in one go after you used Union. Here is an example. Let me know if that answers your question so we can close this thread. Commented Jun 19, 2020 at 20:04
  • 2
    If you delete from top to bottom, you are effectively moving rows up while your iterator i is still stepping forwards. This means that if you had 3:NY 4:NY 5:CA then at i = 3, the first NY would be deleted. now you have 3:NY 4:CA left but your iterator has advanced and i = 4. Since you deleted row 3, the new row 3 still holds the value NY in this case, but your loop has moved on to examine row 4. Commented Jun 19, 2020 at 20:08

3 Answers 3

1

As others have said you need to go from the bottom of your data to the top, if you are only interested in rows 3 to 25 try:

For i = 25 To 3 Step -1
Sign up to request clarification or add additional context in comments.

Comments

0

It's possible with an increasing index, with a While loop.

When you don't delete a row, simply increment the index to test the next one.

When you delete a row, don't advance as the next row is moved to the current row. Instead, reduce the bound by one.

Dim I As Integer, N As Integer
I = 3
N = 25
While I <= N
    If Cells(I, 7) <> "CA" Then
        Rows(I).Delete
        N = N - 1
    Else
        I = I + 1
    End If
Wend

Comments

0

If you still want to go top-down and you know the start and end row you could use a while loop.

Dim i As Integer: i = 3
Dim c As Integer: c = 1

Do While c < (25 - 3 + 2)
    If Cells(i, 7).Value <> "CA" Then
        Rows(i).Delete
    Else
        i = i + 1
    End If
    c = c + 1
Loop

Or using a for loop

For c = 3 To 25
    If Cells(i, 7).Value <> "CA" Then
        Rows(i).Delete
    Else
        i = i + 1
    End If
Next c

2 Comments

Interesting. With this approach, it's actually simpler to replace the Do While with a For loop, as the index c always increases.
@Jean-ClaudeArbaut yep, using a for loop to iterate c would also be syntactically cleaner too. I will add to my ans. Thx!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.