如何保留所有匹配的行(带有条件),并删除所有其他行,包括excel中的空行?

时间:2014-08-21 21:30:29

标签: excel-vba vba excel

以下是我使用的vba,但它只能包含2个条件, 我需要应用3或4个标准。

Sub supprimer()

    Sheets("A").Select

    Dim ws As Worksheet
    Dim rng As Range
    Dim lastRow As Long

    Set ws = ActiveWorkbook.Sheets("A")

    lastRow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row

    Set rng = ws.Range("A1:A" & lastRow)

    ' filter and delete all but header row
    With rng
        .AutoFilter Field:=1, Criteria1:="<>*Agent*", Criteria2:="<>*Receive*"
        .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
    End With

    ' turn off the filters
    ws.AutoFilterMode = False

End sub()

提前致谢 JL

1 个答案:

答案 0 :(得分:1)

我无法找到一种方法来执行具有2个以上条件的And排除过滤器,但此宏将实现您想要的效果。它将删除所有空行和所有不包含条件的行。

Sub supprimer()
    Sheets("A").Select

    Dim ws As Worksheet
    Dim rng As Range
    Dim lastRow As Long

    Set ws = ActiveWorkbook.Sheets("A")
    lastRow = ws.Range("A" & ws.Rows.count).End(xlUp).Row

    For i = lastRow To 2 Step -1
        Set rng = ws.Cells(i, 1)
        If rng.Text <> "" Then
            If Not InStr(1, rng.Text, "Agent") > 0 _
                    And Not InStr(1, rng.Text, "Receive") > 0 _
                    And Not InStr(1, rng.Text, "Criteria3") > 0 _
                    And Not InStr(1, rng.Text, "Criteria4") > 0 _
                    Then
                rng.EntireRow.Delete
            End If
        Else
            'cell is empty, delete this row
            rng.EntireRow.Delete
        End If
    Next i
End Sub