AutoFilter是否可以从Dictionary键中取出包含和不包含的通配符?

我一直在寻找一种方法来筛选超过两个通配符的Excel电子表格。 之前我问过StackOverflow,如果我可以直接在VBA中直接使用两个以上的通配符,而不是在工作表中使用高级filter,因为我的macros大部分是通过PowerShell脚本使用的,它们通过input传递。 这些通配符用于过滤各种电子表格,并保存结果。

一个非常有用的用户提出了一个使用Dictionary键的示例macros,然后将其扩展为接受一个数组作为input,然后遍历数组中的所有项以通配符进行筛选。 优秀,按预期工作!

现在我想扩展它来传递我想排除的更具体的通配符。 比方说,我想包括“A *”和“B *”,而不是“BB *”,所以“BA *”仍然会在那里。 下面的macros可以通过<> BB *通过吗?

hierArray只包含一个由最多10个(但很less超过3个字符)组成的简单string列表。

Public Function multiHier(hierArray As Variant) Dim v As Long, vVALs As Variant, dVALs As Object Dim colNum As Long, hierLen As Integer, hier As Variant Dim rng As Range Set dVALs = CreateObject("Scripting.Dictionary") dVALs.comparemode = vbTextCompare colNum = Application.Match("*ierarchy*", Range("A1:Z1"), 0) 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 For Each hier In hierArray hierLen = Len(hier) Select Case UCase(Left(vVALs(v, 1), hierLen)) Case hier dVALs.Add Key:=vVALs(v, 1), item:=vVALs(v, 1) Case Else End Select Next hier End If Next v If CBool(dVALs.Count) Then 'populated the dictionary; now use the keys .AutoFilter Field:=colNum, Criteria1:=dVALs.keys, Operator:=xlFilterValues Set rng = Worksheets(1).AutoFilter.Range multiHier = rng.Columns(1).SpecialCells(xlCellTypeVisible).Count - 1 Else multiHier = 0 End If End With End With dVALs.RemoveAll: Set dVALs = Nothing End Function 

我要坚持! 这是丢弃的前缀,因为这是单个字符。

  Dim h As Long, hstr As String 'put these at the top with the other var declarations For v = LBound(vVALs, 1) To UBound(vVALs, 1) For h = LBound(hierArray) To UBound(hierArray) 'I just prefer to work this way hstr = hierArray(h) & Chr(42) 'stick a * on the end If Left(hstr, 1) = Chr(33) And LCase(vVALs(v, 1)) Like LCase(Mid(hstr, 2)) Then 'starts with a ! and pattern matches the value 'matched a discard pattern. check to see if it was previously added If dVALs.Exists(vVALs(v, 1)) Then _ dVALs.Remove vVALs(v, 1) 'get rid of it Exit For 'discarded. do not keep checking to add ElseIf LCase(vVALs(v, 1)) Like LCase(hstr) Then If NOT dVALs.Exists(vVALs(v, 1)) Then _ dVALs.Add Key:=vVALs(v, 1), Item:=vVALs(v, 1) End If Next h Next v 

在创buildhierArraystring时,可以通过首先放弃丢弃模式来节省几个周期。 这样,他们不会被添加,然后删除。

在这方面的进一步工作可能会保证切换到完整的正则expression式 ( regexp )模式匹配方法。