VBA:如果存在特定值,则保留行

时间:2016-09-27 17:48:33

标签: arrays excel vba excel-vba

我正在处理我的第一个VBA脚本,并使用http://www.rondebruin.nl/win/s4/win001.htm

中的示例进行操作

这似乎适用于DELETING满足条件“ron”,“Dave”,“Jelle”的行,但是我想制作代码以便它像KEEPS这样的行,例如“Ron A”,“ron B”, “C RON”,“dave A”,“DAVE b”并删除其余部分。换句话说,我想让它不是特定于案例,而不是特定于订单,而是保留而不是删除。

输入:

  • Ron A
  • george h
  • ron B
  • C RON
  • 戴夫A
  • john f
  • JIM R

输出:

  • Ron A
  • ron B
  • C RON
  • 戴夫A

提前谢谢。

Sub Delete_with_Autofilter_Array()
    Dim rng As Range
    Dim calcmode As Long
    Dim myArr As Variant
    Dim I As Long

    With Application
        calcmode = .Calculation
        .Calculation = xlCalculationManual
        .ScreenUpdating = False
    End With

    'Fill in the values that you want to delete
    myArr = Array("ron", "Dave", "Jelle")

    For I = LBound(myArr) To UBound(myArr)

        'Sheet with the data, you can also use Sheets("MySheet")
        With ActiveSheet

            'Firstly, remove the AutoFilter
            .AutoFilterMode = False

            'Apply the filter
            .Range("A1:A" & .Rows.Count).AutoFilter Field:=1, Criteria1:=myArr(I)

            Set rng = Nothing
            With .AutoFilter.Range
                On Error Resume Next
                Set rng = .Offset(1, 0).Resize(.Rows.Count - 1, 1) _
                      .SpecialCells(xlCellTypeVisible)
                On Error GoTo 0
                If Not rng Is Nothing Then rng.EntireRow.Delete
            End With

            'Remove the AutoFilter
            .AutoFilterMode = False
        End With

    Next I

    With Application
        .ScreenUpdating = True
        .Calculation = calcmode
    End With

End Sub

0 个答案:

没有答案