在尝试通过VBA以正常的AutoFilter方式设置2个以上的标准之后,我得知它必须通过高级过滤器来完成.
冒犯的例子:
Worksheets(1).Range("A1").AutoFilter Field:=ColNum, Criteria1:="A*", Operator:=xlOr, Criteria2:="B*", Operator:=xlOr, Criteria3:="C*"
我希望将标准从PowerShell脚本传递给函数(而不是宏).我有一切正常工作,正如预期的1条标准,但现在我想3.
我想我可以改为编写一个宏来插入一个新的工作表,写入标准然后过滤新的范围,但我宁愿先检查首选方式.
要过滤多个通配符,请创建通配符匹配的变量数组,然后使用标准AutoFilter方法的完整值数组.您可以通过将字典对象与其唯一索引属性一起使用来最小化数组.
请考虑以下示例数据.
运行此代码.
Sub multiWildcards() Dim v As Long, vVALs As Variant, dVALs As Object Dim colNum As Long Set dVALs = CreateObject("Scripting.Dictionary") dVALs.comparemode = vbTextCompare colNum = 2 'column B With Worksheets(1) If .AutoFilterMode Then .AutoFilterMode = False With .Cells(1, 1).CurrentRegion vVALs = .Columns(colNum).Cells.Value2 For v = LBound(vVALs, 1) To UBound(vVALs, 1) If Not dVALs.exists(vVALs(v, 1)) Then Select Case UCase(Left(vVALs(v, 1), 1)) Case "A", "B", "C" dVALs.Add Key:=vVALs(v, 1), Item:=vVALs(v, 1) Case Else 'do nothing End Select End If Next v If CBool(dVALs.Count) Then 'populated the dictionary; now use the keys .AutoFilter Field:=colNum, Criteria1:=dVALs.keys, Operator:=xlFilterValues Else Debug.Print "Nothing to filter on; dictionary is empty" End If '.CurrentRegion is now filtered on A*, B*, C* in column B 'do something with it End With End With dVALs.RemoveAll: Set dVALs = Nothing End Sub
结果应该是:
这些结果可以与许多其他通配符方案重复.该Select Case语句是理想的,因为它支持像构建您匹配的集合关键字.通过将值转储开始到常规变量数组中,可以快速完成甚至大行数据的循环.