1

I have to delete all rows that have to cells equal in VBA excel. Here is what i wrote:

Dim i As Long, j As Long
j = Rows.Count
For i = 1 To j
    If Cells(i, 17).Value = Cells(i, 19).Value Then Rows(i).Delete
Next i

But this code is not deleting every line I am looking for. If there are 2 rows with matches the conditions respectively, Excel jumps to another one and leaves this (which is logical), I do not know how to adapt this loop to coming back and delete every searched line

3

2 Answers 2

2

What I am understanding from your code is , it is not iterating all the lines since one of the conditions are getting fulfilled . My recommendation is to reverse loop it. Iterate from the last by using "-1"

Instead of:

For i = 1 To j
    If Cells(i, 17).Value = Cells(i, 19).Value Then Rows(i).Delete
Next i

Do this:

For i = j to 1 Step - 1
    If Cells(i, 17).Value = Cells(i, 19).Value Then Rows(i).Delete
Next i
Sign up to request clarification or add additional context in comments.

7 Comments

This would be a helpful answer if you demonstrated example code.
"For i = j To 1 Step -1" Just put it in you code instead of the existing For loop. Sorry I am not able to test it at this point since my msoffice is having some issue.
Thanks, it helped a lot!
If it really helps you then please like the answer cause that will help others also. :)
@RanadipDutta it's preferable to put a working example of the code in the answer itself, not in the comments. You can edit your answer to be more valuable to others.
|
0

When you delete a row you have to decrement the value of i and update the value of j. Because when you delete a row:

  • the following row is now at the i position
  • the number of rows (j) is reduced by 1 row

1 Comment

Good explanation. This is one possible solution, but the generally preferred approach is to do backwards iteration (e.g., For i = 100 to 1 Step - 1), rather than decrementing a loop counter variable.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.