vba 如何检查字典VBA中是否存在项目(不是键)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28062329/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check whether a item (not the key) exists in the dictionary VBA
提问by lakesh
I would like to check whether a specific value exists in a dictionary. I have created a dictionary as such:
我想检查字典中是否存在特定值。我已经创建了一个字典:
Set Curr = CreateObject("Scripting.Dictionary")
For Index = 1 To NoOfCurr
Curr.Add Index, Cells(15 + Index, 5).Value
Next
I need to check whether a string exists in the dictionary. I have written a code as such:
我需要检查字典中是否存在字符串。我写了这样的代码:
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
IsInArray = arr.Exists(stringToBeFound)
End Function
And it gets called as such:
IsInArray("USD", Curr)
and it returns a false.
它被这样调用:
IsInArray("USD", Curr)
它返回一个假。
I am using Exists function, but it is returning me a False. How do I change IsInArray to see whether the USD is in the Currency dictionary?
我正在使用 Exists 函数,但它返回一个 False。如何更改 IsInArray 以查看美元是否在货币字典中?
回答by Fumu 7
You may misunderstand about 'Dictionary' of VBA.
您可能会误解 VBA 的“词典”。
You can not get 'key' by 'value', but can get 'value' by 'key'.
您不能通过“值”获得“键”,但可以通过“键”获得“值”。
In your code, Curr has indices(integer) as 'key's and currency as 'value's. This is why you can't determine that "USD" is included in the dictionary 'Curr'.
在您的代码中,Curr 将索引(整数)作为“键”,将货币作为“值”。这就是为什么您不能确定“USD”包含在“Curr”词典中的原因。
If you want to check "USD" exist in cells in E column or not, you should use currency as 'key's.
如果要检查 E 列单元格中是否存在“美元”,则应使用货币作为“键”。
Following code may be what you want and you can get right answer by using 'IsInArray("USD", Curr)' .
以下代码可能是您想要的,您可以通过使用 'IsInArray("USD", Curr)' 获得正确答案。
Set Curr = CreateObject("Scripting.Dictionary")
For Index = 1 To NoOfCurr
Curr.Add Cells(15 + Index, 5).Value, Index 'currency is used as keys.
Next
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
IsInArray = arr.Exists(stringToBeFound)
End Function