使用Excel VBA逐个过滤列值(不同)

时间:2015-03-16 18:14:43

标签: excel excel-vba filter vba

我正在尝试逐个过滤列的值。过滤器的值每次都不同。有没有一种方法可以将宏捕获出来。

Sub Macro1()
    Sheets("Open").Select
    'invoice value less than 0
    ActiveSheet.Range("$A$1:$R$2700").AutoFilter Field:=11, Criteria1:="<0", _
        Operator:=xlAnd
    'Selected Country
    ActiveSheet.Range("$A$1:$R$2700").AutoFilter Field:=3, Criteria1:="ARG"
    'Selected invoice#
    ActiveSheet.Range("$A$1:$R$2700").AutoFilter Field:=7, Criteria1:="1007225"
    Range("G528").Select
    ActiveSheet.Range("$A$1:$R$2700").AutoFilter Field:=7, Criteria1:="1015678"
    ActiveSheet.Range("$A$1:$R$2700").AutoFilter Field:=7, Criteria1:="1018523"
    Range("G1").Select
    ActiveSheet.Range("$A$1:$R$2700").AutoFilter Field:=7, Criteria1:="1018962"
End Sub

1 个答案:

答案 0 :(得分:0)

.AutoFilter字段填充到嵌套的变体数组中,并使用排名通过LBoundUBound查看集合。

Sub a1Multi_Filter()
    Dim v As Long, vCRITs As Variant
    Dim vKey As Variant, dCOL7s As New Scripting.Dictionary

    dCOL7s.CompareMode = BinaryCompare

    vCRITs = Array(Array(11, "<0"), _
                   Array(3, "ARG"), _
                   Array(7, "1007225"), _
                   Array(7, "1015678"), _
                   Array(7, "1018523"), _
                   Array(7, "1018962"))

    With ActiveSheet.Cells(1, 1).CurrentRegion
        .AutoFilter
        For v = LBound(vCRITs, 1) To UBound(vCRITs, 1)
            .AutoFilter Field:=vCRITs(v)(0), Criteria1:=vCRITs(v)(1)

            'pause for effect and processing
             MsgBox "array presets" & Chr(10) & "filtered " & .Address(0, 0) & " on column " & Chr(64 + vCRITs(v)(0)) & " for " & vCRITs(v)(1)

            .AutoFilter Field:=vCRITs(v)(0)
        Next v
        .AutoFilter

        For v = 2 To .Rows.Count
            If CBool(Len(.Cells(v, 7).Value)) And Not dCOL7s.Exists(.Cells(v, 7).Value) Then _
                dCOL7s.Add Key:=.Cells(v, 7).Value, Item:=7
        Next v

        For Each vKey In dCOL7s.Keys  'v = 0 To (dCOL7s.Count - 1)
            .AutoFilter Field:=dCOL7s.Item(vKey), Criteria1:=vKey

            'pause for effect and processing
            MsgBox "column 7 special" & Chr(10) & "filtered " & .Address(0, 0) & " on column " & Chr(64 + dCOL7s.Item(vKey)) & " for " & vKey

            .AutoFilter Field:=dCOL7s.Item(vKey)
        Next vKey
    End With
    dCOL7s.RemoveAll: Set dCOL7s = Nothing
End Sub

我给你留下了足够的处理空间,消息文本应该有助于解释变量数组的元素。

在设置了字段索引和条件参数对之后,For ... Next循环使用第一个等级的下限和上限来处理限制。每个集合依次应用,并且我使用msgbox暂停,显示自动过滤器范围,过滤字段和过滤条件。处理完&#39;清除该字段的自动过滤器以准备序列中的下一个。

<强>附录:

我已将G列中的唯一项目集合添加到脚本字典中,然后循环浏览字典键和项目,将每对作为过滤器和条件放在同一.AutoFilter中。要使用脚本字典,您需要进入VBE的工具►参考,并将 Microsoft Scripting Runtime 添加到项目中。这只需要添加一次;并非每台计算机都可以运行,但是如果启动了一个使用脚本字典的新项目,那么它也必须添加到该项目中。