Simple thing is not simple. I am trying to delete rows based on a specific column having data that begins with "2L". So I wrote this code (LastRow is understood):
Sub Cleanup()
For i = 1 To LastRow
If Range("F" & i) Like "2L*" Then Rows(i).delete
Next i
End Sub
The problem is that it does delete rows. I have no idea what it's criteria is for deleting rows but I know it does not get every row with a cell that starts with "2L" in that column as it was written. I start out with 1100 row and it goes down to 677.
I did not create the excel that I am scripting in. the only clue I have is that I did try to format the column and when the format window opens, they don't have a single type. I did try formatting the column of data before I ran the code to be Text but it did not seem to do the trick.
Thoughts?
First, some mandetory house keeping.....
Option Explicit
Option Explicit
Range
) with a worksheetYou should avoid deleting rows as you loop for a few reasons. The main reason is that it can be highly inefficient. Say, for instance, that you have 500 cells that are
Like "2L*"
. That means you will have 500 iterations of rows being deleted.Instead, add every instance of
Like "2L*"
to aUnion
(collection) of cells and once your loop is complete, delete the entireUnion
all at once. Now you just have 1 instance of rows being deleted.Another reason to avoid deleting rows inside your loop is that it forces you to loop backwards. There is nothing wrong with this, it just tends to give people a hard time since it is not intuitive at first. When you delete a row, you shift the range you are looping through up and this causes rows to be skipped. The method below does not need to be looped backwards.
For learning purposes, this is how you would loop backwards. It has less lines than the above method, but is less efficient. If you do decide to go this route, be sure to toggle off
ScreenUpdating
to speed things upI'll borrow from Jeeped here and offer an answer that doesn't require a loop:
Or use autofilter