字典中存在部分内容

问题描述 投票:0回答:2

我正在寻找一种方法来检查字典、Excel - VBA 中是否包含某个值。然而,在这种情况下,简单的

dict.Exists("")
并不是正确的方法,因为搜索值与字典中的值不完全相同。

例如,我在字典中查找单词

apple
,其中包含短语
fruit apple
。所以
apple
在字典中包含为
fruit apple
。尽量避免区分大小写。

目前,我循环字典,这很耗时。

还有类似的补充吗

dict.Exists("*apple*")

有什么想法吗?

excel vba dictionary
2个回答
3
投票

听起来对于(相对未知的)

Filter()
功能来说是一个完美的工作。

Sub Test()

Dim Dict As Object: Set Dict = CreateObject("Scripting.Dictionary")

Dict.Add "Apples", "Found You!"
Dict.Add "Banana", 2
Dict.Add "Cherry", 3
Dict.Add "Date", 4
Dict.Add "Elderberry", 5

r_out = Filter(Dict.Keys, "apple", 1, 1)
If UBound(r_out) > -1 Then
    'Do something with r_out, which is an array of all matched keys
    'For example, traverse filtered keys and return values:
    For i = 0 To UBound(r_out)
        Debug.Print Dict(r_out(i))
    Next
Else
    'Something if no matches are found
    Debug.Print "Bummer"
End If

End Sub

4个参数:

  • Dict.Keys
    可以提供的一维字符串数组;
  • 要搜索的字符串(不区分大小写,所以这里不用担心);
  • 一个布尔值(或等效的 1),告诉函数我们想要返回的值包含字符串;
  • 一个整数 1 (vbTextCompare) 告诉函数我们要比较文本。
我不确定你接下来想做什么...


3
投票

Dictionary.Keys

方法
将返回一个包含所有键的数组。

Excel 的

MATCH

 函数
允许您搜索数组(在 VBA 中可以称为 as Application.Match
)。  这支持通配符,并且
区分大小写 - 但是,请注意,即使字典中的多个键与模式匹配,它也只返回一个单个结果。

两者结合:

Dim vArr AS Variant, vMatch As Variant vArr = dict.keys vMatch = Application.Match("*apple*", vArr, 0) If IsError(vMatch) Then MsgBox "Key Not Found", vbCritical Else MsgBox vArr(vMatch-1), vbInformation 'the -1 is because the Array is Zero-Indexed, but Match returns One-Indexed results End If
    
© www.soinside.com 2019 - 2024. All rights reserved.