我可以循环访问VBA集合中的键/值对吗?

Pet*_*kin 17 collections excel vba excel-vba

在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]);
}
Run Code Online (Sandbox Code Playgroud)

我知道在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
Run Code Online (Sandbox Code Playgroud)

我也知道我使用Scripting.Dictionary VBA对象执行此操作,但我想知道这是否可以使用集合.

我可以遍历VBA集合中的键/值对吗?

Pet*_*ert 31

您无法从集合中检索密钥的名称.相反,您需要使用Dictionary对象:

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
Run Code Online (Sandbox Code Playgroud)

  • 这是一个很好的答案,因为你展示了早期和晚期绑定的例子 - 使其清晰并告知其他人的差异.希望我能加10你! (2认同)