我可以遍历 VBA 集合中的键/值对吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21432222/
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
Can I loop through key/value pairs in a VBA collection?
提问by Peter Rankin
In VB.NET, I can iterate through a dictionary's key/value pairs:
在 VB.NET 中,我可以遍历字典的键/值对:
Dictionary<string, string> collection = new Dictionary<string, string>();
collection.Add("key1", "value1");
collection.Add("key2", "value2");
foreach (string key in collection.Keys)
{
MessageBox.Show("Key: " + key + ". Value: " + collection[key]);
}
I know in VBA I can iterate through the valuesof a Collection object:
我知道在 VBA 中我可以遍历Collection 对象的值:
Dim Col As Collection
Set Col = New Collection
Dim i As Integer
Col.Add "value1", "key1"
Col.Add "value2", "key2"
For i = 1 To Col.Count
MsgBox (Col.Item(i))
Next I
I also know that I do this with a Scripting.Dictionary VBA object, but I was wondering if this is possible with collections.
我也知道我是用 Scripting.Dictionary VBA 对象来做这个的,但我想知道这是否可以用于集合。
Can I iterate through key/value pairs in a VBA collection?
我可以遍历 VBA 集合中的键/值对吗?
回答by Peter Albert
you cannot retrieve the name of the key from a collection. Instead, you'd need to use a Dictionary Object:
您无法从集合中检索密钥的名称。相反,您需要使用字典对象:
Sub LoopKeys()
Dim key As Variant
'Early binding: add reference to MS Scripting Runtime
Dim dic As Scripting.Dictionary
Set dic = New Scripting.Dictionary
'Use this for late binding instead:
'Dim dic As Object
'Set dic = CreateObject("Scripting.Dictionary")
dic.Add "Key1", "Value1"
dic.Add "Key2", "Value2"
For Each key In dic.Keys
Debug.Print "Key: " & key & " Value: " & dic(key)
Next
End Sub