Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA collection: list of keys

After I add some values to the VBA collection, is there any way to retain 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 retain the list of strings:

first string second string third string 

Once again: is there any way to retain the keys?

first key second key third key 

Note: I'm using VBA through AutoCAD 2007

like image 997
Artur Iwan Avatar asked Apr 18 '11 11:04

Artur Iwan


People also ask

How do you use collections in VBA?

To get started with collection first, we need to declare the variable as “Collection.” Since the collection is an object variable, we need to set the object reference by creating a new instance. Now with the variable, we can access all the methods of the collection variable “Col.”

What is the difference between Array and collection in VBA?

Collections in VBA are objects that can store groups of related items, much like an array. Unlike arrays, a single collection can store items of different types because each item in a collection is stored as a Variant.

What is a collection object in VBA?

The Collection object provides a convenient way to refer to a related group of items as a single object. The items, or members, in a collection need only be related by the fact that they exist in the collection. Members of a collection don't have to share the same data type.


2 Answers

If you intend to use the default VB6 Collection, then the easiest you can do is:

col1.add array("first key", "first string"), "first key" col1.add array("second key", "second string"), "second key" col1.add array("third key", "third string"), "third key" 

Then you can list all values:

Dim i As Variant  For Each i In col1   Debug.Print i(1) Next 

Or all keys:

Dim i As Variant  For Each i In col1   Debug.Print i(0) Next 
like image 110
GSerg Avatar answered Oct 11 '22 02:10

GSerg


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 
like image 44
Alex K. Avatar answered Oct 11 '22 02:10

Alex K.