VBA 在集合中按值获取键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12561539/
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
VBA get key by value in Collection
提问by revolutionkpi
Possible Duplicate:
VBA collection: list of keys
可能的重复:
VBA 集合:键列表
Maybe it is a very simple question, but I am new in VBA. I have some data that I want use as Collection(key,value). How can I get key by the value?
也许这是一个非常简单的问题,但我是 VBA 新手。我有一些数据要用作 Collection(key,value)。如何通过值获取密钥?
回答by Mike Woodhouse
I don't think you can do this with the Collection
object.
我不认为你可以用这个Collection
对象来做这件事。
You can, however, use the alternative Dictionary
, which you need to include in your Excel project from the VBA editor: click the "Tools" menus, select "References" and locate "Microsoft Scripting Runtime", after which you should be able to do something like this:
但是,您可以使用替代方法Dictionary
,您需要从 VBA 编辑器将其包含在 Excel 项目中:单击“工具”菜单,选择“参考”并找到“Microsoft Scripting Runtime”,之后您应该能够执行像这样:
Public Sub Test()
Dim dict As New dictionary
dict.Add "a", 1 ' "Add" parameters are reversed compared to Collection
dict.Add "b", 2
dict.Add "c", 3
If KeyFromvalue(dict, 2) = "b" Then
Debug.Print "Success!"
Else
Debug.Print "fail..."
End If
End Sub
Public Function KeyFromvalue(dict As dictionary, ByVal target)
Dim idx As Long
For idx = 0 To dict.Count - 1
If dict.Items(idx) = target Then
KeyFromvalue = dict.Keys(idx)
Exit Function
End If
Next
End Function