vba 如何根据VBA中的键检索字典中的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28059610/
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 retrieve the value in a Dictionary based on key in VBA
提问by lakesh
I have a dictionary as such:
我有一本这样的字典:
Set Desk = CreateObject("Scripting.Dictionary")
For Index = 1 To NoOfDesks
Desk.Add Cells(15 + Index, 4).Value, Index
Next
I am interested in getting the value based on the index. I tried doing this:
我有兴趣根据索引获取值。我尝试这样做:
MsgBox Desk.Items()(1)
But I am not able to get the Value. It is returning a integer. It should be a string. Need some guidance on this.
但我无法获得价值。它返回一个整数。它应该是一个字符串。需要一些指导。
回答by Mathieu Guindon
You're getting exactly what you asked for: when you added the items, you specified Cells(15 + Index, 4)
for a Key, and Index
for an Item. Index
being an Integer
, you're getting an Integer
.
你恰好有你问什么:当你添加的项目,您指定Cells(15 + Index, 4)
为重点,并Index
为项目。Index
成为Integer
,您将获得Integer
.
If possible, add a reference to Microsoft Scripting Runtime
instead of late-binding with CreateObject
: you'll get IntelliSense, which makes it much easier to work with an unfamiliar API:
如果可能,请添加对Microsoft Scripting Runtime
而不是后期绑定的引用CreateObject
:您将获得 IntelliSense,这使得使用不熟悉的 API 变得更加容易:
Your code would look like this:
您的代码如下所示:
Set Desk = New Dictionary
For Index = 1 To NoOfDesks
Desk.Add Index, Cells(15 + Index, 4).Value
Next
One thing to note, is that dictionary keys must be unique - you're [un]lucky to not have duplicates in column 4, otherwise it would be quite apparent that you have inverted the dictionary's key and value.
需要注意的一件事是,字典键必须是唯一的——你很幸运在第 4 列中没有重复,否则很明显你已经反转了字典的键和值。
回答by Vasily
try this:
尝试这个:
Sub test()
Dim Desk As Object, NoOfDesks&, Index&, Key As Variant
Set Desk = CreateObject("Scripting.Dictionary")
NoOfDesks = 100
For Index = 1 To NoOfDesks
Desk.Add Cells(15 + Index, 4).Value, Index
Next
For Each Key In Desk
Debug.Print Key, Desk(Key)
Next
End Sub