gpt4 book ai didi

vba - 自动过滤器可以从字典键中获取包含和非包含通配符吗?

转载 作者:行者123 更新时间:2023-12-03 01:57:55 25 4
gpt4 key购买 nike

我一直在寻找一种方法来过滤具有两个以上通配符的 Excel 电子表格。我之前在 StackOverflow 上询问是否可以直接在 VBA 中将两个以上通配符放入自动筛选器中,而不是在工作表中使用高级筛选器,因为我的宏主要通过 PowerShell 脚本使用,这些脚本会传递输入。这些通配符用于过滤各种电子表格并保存结果。

一位非常有帮助的用户提出了一个答案,给出了一个使用字典键的示例宏,然后我将其扩展为接受数组作为输入,然后循环遍历数组中的所有项目以作为通配符进行过滤。非常好,按预期工作!

现在我想扩展它以传递我想要排除的更具体的通配符。举例来说,我想包含“A*”和“B*”,但不包含“BB*”,这样“BA*”仍然存在。下面的宏可以通过 <>BB* 来工作吗?

hierArray 只包含一个简单字符串列表,最多包含 10 个字符(但很少超过 3 个字符)。

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

创建 hierArray 字符串时,可以通过首先放置丢弃模式来节省一些周期。这样,它们就不会被添加然后被删除。

该领域的任何进一步工作都可能需要切换到完整的正则表达式 ( ) 模式匹配方法。

关于vba - 自动过滤器可以从字典键中获取包含和非包含通配符吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34614417/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com