如何在VBA中过滤掉许多条件?

时间:2018-12-10 18:12:41

标签: excel vba excel-vba

我一直在寻找代码来从不需要的列表中过滤条件。我有一个适用于过滤所需标准的代码,但是当我尝试将其反转时,出现“不匹配”错误。

这是我的代码,用于过滤不需要的条件。

Sub Filters()              
    Dim IntP As Worksheet 'sheet where the main table is
    Dim Param As Worksheet 'sheet where my parameters are
    Dim iRange As Range 'the range of my table
    Dim range1 As Range 'the range that contains the list I want to filter in iRange

    Set IntP = Worksheets("Internet Promotions")
    Set Param = Worksheets("Sheet1")
    Set iRange = IntP.Range("A1", ("AU" & IntP.Range("A" & Rows.Count).End(xlUp).Row)) 'range of my table
    Set range1 = Param.Range("D2", ("D" & Param.Range("D" & Rows.Count).End(xlUp).Row)) 'range of my paramters

    Dim var1 As Variant
    Dim sArray() As String
    Dim i As Long

    '---------------Filter-----------------------   
    var1 = range1.Value
    ReDim sArray(1 To UBound(var1))

    For i = 1 To (UBound(var1))
        sArray(i) = var1(i, 1)
    Next

    iRange.AutoFilter Field:=21, Criteria1:="<>" & sArray, Operator:=xlFilterValues  
End Sub

我不明白为什么这不起作用。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

尝试在多个字段上使用多个条件过滤数据。

请参见以下示例。

enter image description here

Sub filter_col()

'Apply filters on two columns

With ActiveSheet.Range("B3:D6")
    .AutoFilter field:=2, Criteria1:="New-York"
    .AutoFilter field:=3, Criteria1:=">1300000"
End With

End Sub

enter image description here