With a VBA Collection (in Word), can I access both the data and the key stored?

Using VBA in Word, if I have stored strings in a collection, each with a different Key, is it possible to go through all the members of the collection and retrieve not only the stored string but also the key that accesses the string?
     The following code displays the strings of data stored inside "MyCollection":
     
     Dim x as Variant
     For each x in MyCollection
         Msgbox x
     Next x

     What I need is something that will also tell me the keys that access those data.

     Thanks!

     j.r.a.
JohnRobinAllenRetired professor of FrenchAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Patrick MatthewsCommented:
As far as I know, you cannot access the keys in a Collection object directly.

You may want to try using a Dictionary object as well.  The Dictionary object has a Keys method, which returns an array of all of the keys in the Dictionary.



Dim dic As Object
Dim arr As Variant
Dim Counter As Long

Set dic = CreateObject("Scripting.Dictionary")
dic.Add "Key1", "Value1"
dic.Add "Key2", "Value2"
dic.Add "Key3", "Value3"

arr = dic.Keys

For Counter = LBound(arr) to UBound(arr)
    MsgBox "Key is: " & arr(Counter) & "; Value is:" & dic.Item(arr(Counter))
Next

Set dic = Nothing

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
JohnRobinAllenRetired professor of FrenchAuthor Commented:
Each day I am more and more appalled at how little I know about VBA. The Dictionary is the perfect solution for my problem. I am indebted to Matthew for his help.
    j.r.a.
0
Patrick MatthewsCommented:
Glad to help :)

The Dictionary is one of my favorite objects.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft Word

From novice to tech pro — start learning today.