繁体   English   中英

vba代码在特定列的所有单元格中搜索0(如果找到),然后删除该行

[英]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

上面提到的代码没有显示任何错误,但没有删除Column(“ AI”)单元格为0的整个行。请帮助我获取正确版本的代码。

您应该从头开始:

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

要删除所需的行,无需遍历这些行。

您可以使用自动过滤器一次删除所有行。

试试这个...

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的答案可以解决您的问题,如果要删除很多行,将需要很长时间来处理它。

更快的解决方案是使用DelRng对象,每次迭代并满足条件时,都可以使用Union函数将该行添加到DelRng 最后,您一次删除所有行。

请尝试以下代码:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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