You might want to start from a different path. When you delete a line, all previous lines are shifted. You take this into account, but the reverse loop is easier (for me anyway) to understand than to track when I shift the current position in the loop:
For i = count To 21 Step -1
Also, you rely 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") > 0
Application.WorksheetFunction
requires much more processing power, and depending on what you are trying to do, it may take significantly longer. Also for this proposed change, code size is reduced and it becomes easier to read without it.
Your count
can also be obtained without A.WF
:
- Excel 2000/03:
count = Range("AF65536").End(xlUp).Row
- Excel 2007/10:
count = Range("AF1048576").End(xlUp).Row
- Independent version:
count = Range("AF" & Rows.Count).End(xlUp).Row
Another thing you can do (and should do in this case) is to combine your If
statements into one.
By making these changes, you will receive:
Sub deleteRows() Dim count As Integer count = Range("AF" & Rows.Count).End(xlUp).Row Dim i As Integer For i = count To 21 Step -1 If Len(Range("B" & i).value) > 0 Then If InStr(Range("B" & i).value, "OSR Platform") > 0 Or InStr(Range("B" & i).value, "IAM") > 0 Then Range("B" & i).Interior.Color = RGB(255, 0, 0) End If End If Next i End Sub
If this does not help, you can go through the code line by line. Add a breakpoint and execute with F8 . Select the variables in your code, right-click, select "Add Watch ...", click "OK", ( here is a great resource that will help you with your debugging in general ) and pay attention to the following:
- Which line gets into the error?
- What is the value of
i
and count
when this happens? (add hours to these variables to help)