2015-06-04 92 views
2

我有一本字典,其中每個VALUE是另一個字典。在我的代碼中,我使用.Items()(i)通過頂級字典進行循環。順便說一下,它需要保持這種方式。vba字典 - 從項目返回KEY()

Dim dic As New Scripting.Dictionary 
Dim myValue As New Scripting.Dictionary 

For i = 0 to dic.count-1 
    ' 
    ' the VALUE of the KEY/VALUE pair is... 
    set myValue = dic.Items()(i) 
    ' 
    ' how do I retrieve the KEY??? 
    ' 
Next i 

我的問題:

如何獲取頂級詞典在這個循環結構的關鍵所在?這可能是非常明顯的,我只是在這裏畫一個空白。

+0

是的,就是這樣。我從來沒有用過。凱利(我)之前。謝謝! – twegner

+0

您可以使用'For Each Loop'循環訪問'Dictionary Object'的'Keys'集合。這就是它的目的。 – L42

回答

7
Sub Tester() 

    Dim d, i 
    Set d = CreateObject("scripting.dictionary") 

    d.Add "K1", "v1" 
    d.Add "K2", "v2" 
    d.Add "K3", "v3" 

    For i = 0 To d.Count - 1 
     Debug.Print d.items()(i), d.keys()(i) 
    Next i 

End Sub 
4

或者,也許這樣的:

Dim key As Variant 

With dic 
    For Each key In .Keys 
     Debug.Print key, .Item(key) 
    Next 
End With