Search code examples
vbacollections

VBA collection: list of keys


After I add some values to the VBA collection, is there any way to retrieve the list of all keys?

For example

Dim coll as new  Collection
Dim str1, str2, str3

str1="first string"
str2="second string"
str3="third string"

coll.add str1, "first key"
coll.add str2, "second key"
coll.add str3, "third key"

I know how to retrieve the list of strings:

Dim x As Variant
For Each x In coll
    Debug.Print x
Next x

will produce the following...

first string
second string
third string

Is there a similarly concise way to retrieve just the keys?

first key
second key
third key

Note: I'm using VBA through AutoCAD 2007


Solution

  • I don't thinks that possible with a vanilla collection without storing the key values in an independent array.

    The easiest alternative to do this is to add a reference to the Microsoft Scripting Runtime & use a more capable Dictionary instead:

    Dim dict As Dictionary
    Set dict = New Dictionary
    
    dict.Add "key1", "value1"
    dict.Add "key2", "value2"
    
    Dim key As Variant
    For Each key In dict.Keys
        Debug.Print "Key: " & key, "Value: " & dict.Item(key)
    Next