2014-01-29 98 views
12

在VB.NET中,我可以通過一個字典的鍵/值對迭代:我可以循環訪問VBA集合中的鍵/值對嗎?

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]); 
} 

我知道在VBA我可以通過值的集合對象的迭代

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 

我也知道我用Scripting.Dictionary VBA對象來做這件事,但我想知道這是否可以用於集合。

我可以遍歷VBA集合中的鍵/值對嗎?

+1

據我所知,你,如果你想通過鍵/值對迭代can't..You應該使用'Dictionary' .. –

回答

26

您無法從集合中檢索密鑰的名稱。相反,你需要使用一個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 
+1

+1早期綁定:) –

+1

感謝您的早期綁定,新的詞典沒有工作。但是New Scripting.Dictionary確實:D Thx了。 – danger89

+0

在我的VBA腳本中不起作用。我需要一個lib或其他東西? –