虽然AutoFilter 方法中每个字段最多有两个直接通配符,但模式匹配可用于创建一个数组,用Operator:=xlFilterValues选项替换通配符。Select Case 语句有助于通配符匹配。
第二个字段是简单的 Criteria1 和 Criteria2 直接匹配,使用Operator:=xlOr连接这两个条件。
Sub multiWildcardFilter()
Dim a As Long, aARRs As Variant, dVALs As Object
Set dVALs = CreateObject("Scripting.Dictionary")
dVALs.CompareMode = vbTextCompare
With Worksheets("Sheet1")
If .AutoFilterMode Then .AutoFilterMode = False
With .Cells(1, 1).CurrentRegion
'build a dictionary so the keys can be used as the array filter
aARRs = .Columns(2).Cells.Value2
For a = LBound(aARRs, 1) + 1 To UBound(aARRs, 1)
Select Case True
Case aARRs(a, 1) Like "MK1454*"
dVALs.Add Key:=aARRs(a, 1), Item:=aARRs(a, 1)
Case aARRs(a, 1) Like "MK1467*"
dVALs.Add Key:=aARRs(a, 1), Item:=aARRs(a, 1)
Case aARRs(a, 1) Like "MK1879*"
dVALs.Add Key:=aARRs(a, 1), Item:=aARRs(a, 1)
Case Else
'no match. do nothing
End Select
Next a
'filter on column B if dictionary keys exist
If CBool(dVALs.Count) Then _
.AutoFilter Field:=2, Criteria1:=dVALs.keys, _
Operator:=xlFilterValues, VisibleDropDown:=False
'filter on column E
.AutoFilter Field:=5, Criteria1:="PROD", Operator:=xlOr, _
Criteria2:="RISK", VisibleDropDown:=False
'data is filtered on MK1454*, MK1467* or MK1879* (column B)
'column E is either PROD or RISK
'Perform work on filtered data here
End With
If .AutoFilterMode Then .AutoFilterMode = False
End With
dVALs.RemoveAll: Set dVALs = Nothing
End Sub
如果要将排除项¹添加到过滤中,则应将其逻辑放置在 Select..End Select 语句的顶部,以免通过误报将它们添加到其他匹配条件。
应用自动筛选方法之前
应用带有多个通配符的自动筛选后
¹请参阅高级筛选条件可以在 VBA 中而不是在范围内吗?并且AutoFilter 可以从 Dictionary 键中获取包含和非包含通配符吗?有关向字典的过滤器集添加排除项的更多信息。