vba Dictionary - returning KEY from Items()
17,255
Solution 1
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
Solution 2
Or maybe this:
Dim key As Variant
With dic
For Each key In .Keys
Debug.Print key, .Item(key)
Next
End With
Author by
twegner
Updated on July 10, 2022Comments
-
twegner almost 2 years
I have a dictionary where each
VALUE
is another dictionary. In my code I loop through the top-level dictionary using.Items()(i)
. By the way, it needs to stay this way.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
My question:
How do I retrieve the KEY of the top-level dictionary in this loop structure? This is probably super obvious, I'm just drawing a blank here.
-
twegner almost 9 yearsYep, that's it. I never used .Keys(i) before. Thanks!
-
L42 almost 9 yearsYou can always loop through the
Keys
collection of theDictionary Object
usingFor Each Loop
. That is what it's there for.
-