• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 525
  • Last Modified:

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.


  • 2
1 Solution
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))

Set dic = Nothing

Open in new window

JohnRobinAllenAuthor 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.
Patrick MatthewsCommented:
Glad to help :)

The Dictionary is one of my favorite objects.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now