删除行的有效方法(Multiple Criterias)VBA

时间:2014-11-03 10:56:48

标签: excel vba excel-vba

我有一张表格,其中在Col A中有一个字符串A,而字符B由字符串B组成。

我想在Col A中保留“Begründung”字样,在Col B中保留“Nein”字样。

我正在使用以下来自这些来源的代码Efficient way to delete entire row if cell doesn't contain '@'& Delete Row based on Search Key VBA

Sub KeepOnlyAtSymbolRows()
    Dim ws As Worksheet
    Dim rng As Range
    Dim lastRow As Long

    Set ws = ActiveWorkbook.Sheets("Sheet1")

    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:="<>*Begründung*"
        .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
    End With

    ' turn off the filters
    ws.AutoFilterMode = False
End Sub

我想为Col B添加另一个标准。无论在Col B'Nein'遇到哪一行,其余部分都被删除,但同时保留了Col A中的Begrüundung,其余部分被删除。

换句话说,无论在表格中遇到“Begründung”和“Nein”这些词,这些行都会被保留,其余行将被删除。

如果你们中的任何人能提供帮助,我将非常感激。

1 个答案:

答案 0 :(得分:2)

试试这个:

Sub DeleteWithMultipleColumnsCriterias()
    Dim ws As Worksheet
    Dim rng As Range
    Dim lastRow As Long

    Set ws = ActiveWorkbook.Sheets("Sheet1")

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

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

    ' filter and delete all but header row
    With rng
        .AutoFilter Field:=1, Criteria1:="<>*Begründung*"
        .AutoFilter Field:=2, Criteria1:="<>*Nein*"
        .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
    End With

    ' turn off the filters
    ws.AutoFilterMode = False
End Sub