I’m trying to run a macro that will delete rows that don’t contain a particular value in column B. Here’s my code:
Sub deleteRows()
Dim count As Integer
count = Application.WorksheetFunction.CountA(Range("AF:AF"))
Dim i As Integer
i = 21
Do While i <= count
If (Application.WorksheetFunction.IsNumber(Application.WorksheetFunction.Search("OSR Platform", Range("B" & i))) = False) Then
If (Application.WorksheetFunction.IsNumber(Application.WorksheetFunction.Search("IAM", Range("B" & i))) = False) Then
Rows(i).EntireRow.Delete
i = i - 1
count = count - 1
End If
End If
i = i + 1
Loop
End Sub
Now what it SHOULD be doing is the following:
1.) Find the number of rows to go through and set that as count (this works)
2.) Start at row 21 and look for “OSR Platform” and “IAM” in column B [this kind of works (see below)]
3.) If it finds neither, delete the entire row and adjust the count and row number as necessary (this works)
For some reason, whenever the code gets to the first If statement, an error window with a red X pops up that just says “400.” As far as I can tell, I have written everything syntactically soundly, but clearly there’s something wrong.
You may want to start by looping the other way. When you delete a line, all the previous lines are shifted. You account for this, but a reverse loop is simpler (for me anyways) to understand than keeping track of when I’ve offset the current position within the loop:
For i = count To 21 Step -1Also, you’re relying too much on
Application.WorksheetFunction:(Application.WorksheetFunction.IsNumber(Application.WorksheetFunction.Search("OSR Platform", Range("B" & i))) = False)to
InStr(Range("B" & i).value, "OSR Platform") > 0Application.WorksheetFunctiontakes much more processing power, and depending on what you are trying to accomplish, this can take a significantly longer amount of time. Also for this suggested change, the code size is reduced and becomes easier to read without it.Your
countcan also be obtained withoutA.WF:count = Range("AF65536").End(xlUp).Rowcount = Range("AF1048576").End(xlUp).Rowcount = Range("AF" & Rows.Count).End(xlUp).RowOne more thing is that you can do (and should do in this case) is combine your
Ifstatements into one.Making these changes, you end up with:
If this does not help, then can you step through the code line by line. Add a breakpoint, and step through with F8. Highlight the variables in your code, right-click, choose “add Watch…”, click “OK”, (Here’s an excellent resource to help you with your debugging in general) and note the following:
iandcountwhen that happens? (add a watch on these variables to help)