Home > Net >  Delete all cells in a range if a specific value is found on a cell - VBA
Delete all cells in a range if a specific value is found on a cell - VBA

Time:03-02

I need to perform the below action:

From a data range in an excel sheet in need to delete all the values if a given condition is found in a specific column, here is the code i wrote: (delete all the rows that have FLWE or FW in the first cell)

Sub cancellaflw()

 Dim RowFINE, LastRowDati2 As Long
 
 With ThisWorkbook.Sheets("Dati")

RowFINE = 1
LastRowDati2 = ThisWorkbook.Sheets("Dati").Cells(Rows.count, 1).End(xlUp).Row

For RowFINE = 1 To LastRowDati2
If .Cells(RowFINE, 1) Like "FLWE*" Or .Cells(RowFINE, 1) Like "FW*" Then
.Range("A" & RowFINE & ":X" & RowFINE).Delete
RowFINE = RowFINE - 1
End If

Next RowFINE
End With

 
 End Sub

Unfortunately this is not working, any idea on the reason why?

Thanks, Matteo

CodePudding user response:

You have made a very common newbie mistake. You need to change

For RowFINE = 1 To LastRowDati2

to

For RowFINE = LastRowDati2 to 1 step -1

This means that you are now not changing the range over which you are iterating. With your current code when you delete row 3, then row 4 automatically becomes row 3, but Rowfine doesn't know this has happened. So increments to 4 so you have effectively skipped over a row.

  • Related