【问题标题】:Is there a way to filter on the basis of 10+ criteria within each cell?有没有办法根据每个单元格中的 10 多个标准进行过滤?
【发布时间】:2021-01-24 03:57:03
【问题描述】:

我有一个 Excel 工作表,我需要在其中根据多个条件过滤行。

信息有时位于单元格的中间。
例如,
C12:肯尼迪国际机场 2018 年 1 月咖啡
C13:LGA 01/2018 比萨
C14:SFA 意大利面 2017 年 3 月。

我需要根据尽可能多的 2018 年 1 月写法来过滤与 2018 年 1 月相关的行,以筛选出几百行。

我尝试了以下方法:

Sub myFilter()
    
    Dim dic As Object
    Dim eleData As Variant
    Dim eleCrit As Variant
    Dim arrData As Variant
    Dim vTst As Variant
    Set dic = CreateObject("Scripting.Dictionary")
    vTst = Array("*Jan 2018*", "*JAN 2018*", "*01/2018*", "*012018*", "*12018*")
    With ActiveSheet
        .AutoFilterMode = False
        arrData = .Range("B1:B" & .Cells(.Row.Count, "B").End(xlUp).Row)
        For Each eleCrit In vTst
            For Each eleData In arrData
                If eleData Like eleCrit Then dic(eleData) = vbNullString
            Next
        Next
        .Columns("B:B").AutoFilter Field:=1, Criteria:=dic.Keys, Operator:=xlFilterValues
    End With
End Sub

这段代码给出了

运行时错误
“对象不支持此属性或方法”。

如果代码在我的小样本上运行,我会调整代码以适应更大的数据集。

【问题讨论】:

    标签: excel vba filter


    【解决方案1】:

    Excel 被限制为使用通配符搜索最多 2 个单词,所以也许您正在寻找类似的东西,一个针对该问题的解决方法

    Sub myFilter()
    
    Dim Crit() As Variant
    Dim cri() As String
    Dim cri2() As String
    Dim i As Integer
    Dim j As Integer
    Dim k As Integer
    Dim rng As Range
    
    Crit = Array("Jan 2018", "JAN 2018", "01/2018", "012018", "12018")
    Set rng = ActiveSheet.Range("B1:B" & ActiveSheet.Cells(ActiveSheet.Rows.Count, "B").End(xlUp).row) 'HERE Range
    
    ReDim Preserve cri(UBound(Crit))
    ReDim Preserve cri2(1)
    
    
    
    For i = LBound(Crit) To UBound(Crit)
    
        cri(i) = "=*" & Crit(i) & "*"
    
    
        rng.AutoFilter Field:=1, Criteria1:=cri(i), Operator:=xlFilterValues 'HERE Field in the Range i.e column Number
    
        j = UBound(cri2)
    
        ReDim Preserve cri2(j + rng.SpecialCells(xlCellTypeVisible).Count)
    
            For Each rw In rng.SpecialCells(xlCellTypeVisible).Rows
    
                    cri2(j + 1) = Cells(rw.row, "B").Value 'HERE Column that corresponds to the Filtered Field in this case B
                    Debug.Print cri2(j + 1)
                    j = j + 1
    
            Next
    
    Next
    
    rng.AutoFilter Field:=1, Criteria1:=cri2, Operator:=xlFilterValues 'HERE Again Field to Filter On
    
    End Sub
    

    注意:

    • 不需要在数组中添加*,它已经这样做了。
    • 取自Here
    • 如果您想修改代码并更改要过滤的范围或字段,我在代码中标记了 4 个位置。相应地更改变量。

    工作:

    【讨论】:

    • 哦,非常感谢您分享代码,它成功了!!!抱歉,我自己没有找到。=)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-20
    • 1970-01-01
    • 2022-11-27
    • 1970-01-01
    • 1970-01-01
    • 2020-07-31
    • 1970-01-01
    相关资源
    最近更新 更多