excel vba如果一列中有0值则删除整行

时间:2019-03-21 10:27:13

标签: excel vba

我想制作一个VBA代码,如果列'D'中的值为0,则会自动删除整行。im使用此代码,但是当我尝试运行它时,出现一个错误,提示“应用程序定义或对象-定义的错误”。有人知道为什么吗?还是有其他方法可以做到这一点?

Sub deletezeros()
    Dim c As Range
    Dim searchrange As Range
    Dim i As Long

    Set searchrange = Worksheets("sheet2").Range("D2", ActiveSheet.Range("D123432").End(xlUp))

    For i = searchrange.Cells.Count To 1 Step -1
        Set c = searchrange.Cells(i)
        If c.Value = "0" Then c.EntireRow.Delete
    Next i
End Sub

1 个答案:

答案 0 :(得分:0)

您可以尝试更简单的方法吗?喜欢:

    Dim SH As Worksheet
    Set SH = ThisWorkbook.Sheets("sheet2")
    Dim LR As Long
    LR = SH.Columns(4).Find("*", searchorder:=xlByRows, LookIn:=xlValues, searchdirection:=xlPrevious).Row
   '-----
    For i = LR To 2 Step -1
        If SH.Cells(i, 4).Value = "0" Then
            SH.Cells(i, 4).EntireRow.Delete
        End If
    Next i