Yeah I know whats wrong here. When you delete the i row, it is possible that the next one, which would be i+1, also meets the criteria but won't get deleted cause it will have turned into the i row, meaning the code won't check it again. So we have to change the current i when the row gets deleted. Also, as the total amount of written rows in your sheet will be changing, we need to update the end of the for accordingly. When this happens, I choose to use the Do Loop strategy instead.
Option Explicit
Sub Button5_Click()
Dim i As Long 'Is the counter for the loop, will be our line number
Dim j As Long 'Counts the amount of active lines in sheet
Sheets("New").Activate
Application.Calculation = xlCalculationManual 'Will improve the time it takes to run
Application.ScreenUpdating = False 'Will stop screen flickering
i = 0
j = Cells.SpecialCells(xlCellTypeLastCell).Row
Do
i = i + 1
If Not (Cells(i, 18).Value Like "Cancelled*") And Cells(i, 8).Value = "" Then
Cells(i, 8).EntireRow.Delete
i = i - 1 'When we delete the row, to avoid not looking at the next one we need to go back
j = j - 1 'When we delete the row, our sheet has less lines
End If
If i = j Then
Exit Do 'If we reach the last row, the loop ends
End If
Loop
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub
If you want it not to be like "Cancelled*" then you ccan add exactly that into the code, the Not operator returns True when the statement inside is False. You could be using the <>, but you would have to change it to what I had shown you before:
If Left(Cells(i, 5).Value, 9) <> "Cancelled"
because you need to make sure that what you are checking is exactly "Cancelled". I mean the <> does not work as the Like statement does, in which you can put in the * at the end to say "anything can go after this", but it actually checks for exact matches.
The screen flickering is caused by the fact that we didn't turn off the ScreenUpdating, so you are seeing it delete the rows.
I hope that helps. Please tell me if you have any other issues with this.
Bookmarks