简体   繁体   中英

vba code to search for 0 in all the cells of particular column if found then delete that row

lRow = Cells(Rows.Count, "AI").End(xlUp).Row
For iCntr = 1 To lRow
    If Cells(iCntr, 35) = 0 Then
        Rows(iCntr).Delete
    End If
Next

The above-mentioned code is not showing any error but not deleting the entire rows in which Column("AI") cells are 0. Kindly help me with the correct version of the code.

You should work from the bottom up:

lRow = Cells(Rows.Count, "AI").End(xlUp).Row
For iCntr = lRow To 1 Step -1
If Cells(iCntr, 35) = 0 Then
Rows(iCntr).Delete
End If
Next

To delete the desired rows, you don't need to loop through the rows.

You may use autofilter to delete all the rows at once.

Give this a try...

Sub DeleteRows()
Dim lRow As Long
Application.ScreenUpdating = False
lRow = Cells(Rows.Count, "AI").End(xlUp).Row
ActiveSheet.AutoFilterMode = False
With Range("AI1:AI" & lRow)
    .AutoFilter field:=1, Criteria1:=0
    If .SpecialCells(xlCellTypeVisible).Cells.Count > 1 Then
        Range("AI2:AI" & lRow).SpecialCells(xlCellTypeVisible).EntireRow.Delete
    End If
    .AutoFilter
End With
Application.ScreenUpdating = True
End Sub

@Tim Williams answer would solve your problem, it will take you a long time to process it if you are trying to delete a lot of rows.

A faster solution will be to use DelRng object, which every time you iterate, and the criteria is met, you add that row to DelRng with Union function. At the end, you delete all of the rows at once.

Try the code below:

Dim DelRng As Range

With Sheets("Sheet1") ' modify to your sheet's name (allways qualify with the worksheet object)

    lRow = .Cells(.Rows.Count, "AI").End(xlUp).Row

    For iCntr = 1 To lRow
        If .Cells(iCntr, 35) = 0 Then
            If Not DelRng Is Nothing Then
                Set DelRng = Application.Union(DelRng, .Rows(iCntr))
            Else
                Set DelRng = .Rows(iCntr)
            End If
        End If
    Next

    ' delete the entire rows at once >> will save you a lot of time
    DelRng.Delete

End With

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM