Solved

VBA Word: Store and retrieve info in a collection

Posted on 2013-11-30
6
467 Views
Last Modified: 2013-12-05
I am using Word VBA and want to store some data in a Collection using two arguments: a Key and some data associated with that key. Here is the code:
Sub Test()
     '      Test storing and retrieving some data.
     '      Declarations
     Dim ACollection As New Collection
     Dim KeyData As Variant
     Dim ItemData As Variant
     
     '      Make up some data: a key and something related to that key
     KeyData = "5"
     ItemData = "Test"

     ACollection.Add Key:=KeyData, Item:=ItemData    'Add items to the collection

       '    Now try to retrieve that information
       Dim MyObject As Variant
       For Each MyObject In ACollection
              ItemData = MyObject   '     half of the information stored is retrieved
              Key Data = ??               '     how do I get the Key used in storing the information?
       Next
End Sub

Of course my actual code is a bit more complex. The above just shows the essence of the problem: to retrieve both the data stored and the key used for storing it.

Thanks for any help
JRA in Priddis, Alberta
0
Comment
Question by:JohnRobinAllen
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
6 Comments
 
LVL 35

Accepted Solution

by:
Robert Schutt earned 500 total points
ID: 39687469
Some googling reveals a possible solution using low-level functions calls but I'm not sure that is what you really need.

The Collection class you're using above seems specifically meant to be able to retrieve values when you know the key. Solutions I see around the 'net focus on using a Dictionary or repeating the key in a custom object that you then add to the Collection instead of just the value you put there now.

Using a Dictionary seems the most efficient change in your case:
Sub Test()
     '      Test storing and retrieving some data.
     '      Declarations
     Dim ACollection As New Scripting.Dictionary
     Dim KeyData As Variant
     Dim ItemData As Variant
     
     '      Make up some data: a key and something related to that key
     KeyData = "5"
     ItemData = "Test"
     ACollection.Add Key:=KeyData, Item:=ItemData    'Add items to the collection
     KeyData = "6"
     ItemData = "Test2"
     ACollection.Add Key:=KeyData, Item:=ItemData    'Add items to the collection

       '    Now try to retrieve that information
       Dim MyObject As Variant
       For Each MyObject In ACollection
              KeyData = MyObject
              ItemData = ACollection(KeyData)
              Debug.Print "Key: " & KeyData & " => Item: " & ItemData
       Next
End Sub

Open in new window

For that to work you need to add a reference to your VBA project (or use late binding). To add a reference use the menu "Tools | References" in the VBA editor. Then find "Microsoft Scripting Runtime" and check it.
add-refTo use late binding, change line 4 above to:
Dim ACollection As Object: Set ACollection = CreateObject("Scripting.Dictionary")

Open in new window

0
 
LVL 14

Expert Comment

by:Faustulus
ID: 39687487
You need to set up a class for your collection. Find the whole process and its code very nicely described at this link.
0
 
LVL 15

Expert Comment

by:DrTribos
ID: 39697937
I think you can achieve this with a scripting dictionary...

Sub FillColourDictionary(ByVal dict As Scripting.Dictionary, bNumberKey As Boolean)
Dim strColours As String
Dim arrColourLines() As String
Dim c As Integer
Dim ColourItem() As String
strColours = "wdColorAqua;13421619/wdColorAutomatic;-16777216/wdColorBlack;0/wdColorBlue;16711680/wdColorBlueGray;10053222/" & _
            "wdColorBrightGreen;65280/wdColorBrown;13209/wdColorDarkBlue;8388608/wdColorDarkGreen;13056/wdColorDarkRed;128/" & _
            "wdColorDarkTeal;6697728/wdColorDarkYellow;32896/wdColorGold;52479/wdColorGray05;15987699/wdColorGray10;15132390/" & _
            "wdColorGray125;14737632/wdColorGray15;14277081/wdColorGray20;13421772/wdColorGray25;12632256/wdColorGray30;11776947/" & _
            "wdColorGray35;10921638/wdColorGray375;10526880/wdColorGray40;10066329/wdColorGray45;9211020/wdColorGray50;8421504/" & _
            "wdColorGray55;7566195/wdColorGray60;6710886/wdColorGray625;6316128/wdColorGray65;5855577/wdColorGray70;5000268/" & _
            "wdColorGray75;4210752/wdColorGray80;3355443/wdColorGray85;2500134/wdColorGray875;2105376/wdColorGray90;1644825/" & _
            "wdColorGray95;789516/wdColorGreen;32768/wdColorIndigo;10040115/wdColorLavender;16751052/wdColorLightBlue;16737843/" & _
            "wdColorLightGreen;13434828/wdColorLightOrange;39423/wdColorLightTurquoise;16777164/wdColorLightYellow;10092543/" & _
            "wdColorLime;52377/wdColorOliveGreen;13107/wdColorOrange;26367/wdColorPaleBlue;16764057/wdColorPink;16711935/" & _
            "wdColorPlum;6697881/wdColorRed;255/wdColorRose;13408767/wdColorSeaGreen;6723891/wdColorSkyBlue;16763904/" & _
            "wdColorTan;10079487/wdColorTeal;8421376/wdColorTurquoise;16776960/wdColorViolet;8388736/wdColorWhite;16777215/wdColorYellow;65535"
            
            
arrColourLines = Split(strColours, "/")
For c = 0 To UBound(arrColourLines)
    ColourItem = Split(arrColourLines(c), ";")
    If bNumberKey Then
        dict.Add ColourItem(1), ColourItem(0)
        ''debug.print ColourItem(1), dict.item(ColourItem(1))
    Else
        dict.Add ColourItem(0), ColourItem(1)
        ''debug.print ColourItem(0), dict.item(ColourItem(0))
    End If
Next

End Sub

Open in new window

Rgonzo might remember a portion of this code from an earlier question...
0
On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

 
LVL 15

Expert Comment

by:DrTribos
ID: 39697938
Ooops sorry I just noticed this is basically what robert_schutt is suggesting as well....

in a nutshell you can use the key of the dictionary to access the variable... it's really cool.

HTH
0
 

Author Comment

by:JohnRobinAllen
ID: 39698716
The solution was more complicated than I had thought, so I bumped the point count up to the max. However, the solution is already posted. Comments on that to come when I accept the proposed solution in less than a minute.
0
 

Author Closing Comment

by:JohnRobinAllen
ID: 39698737
This first solution proposed is the easiest and best one proposed. However one must use the revised line 4 to use late binding. My programs go out to neophytes and I cannot ask them to add the reference to Scripting Runtime. The revised line 4 obviates the necessity of the more complex solution.
     The subsequent comments posted are most interesting, but the first solution works perfectly with no additional coding.
     Many thanks! One more nail is now hit on the head.
     Hurrah for EE and for magi like Mr. Schutt

     JRA in Priddis, Alberta, Canada
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

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

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Microsoft Word is a program we have all encountered at some point, but very few of us have dug deep into its full scope of features, let alone customized it to suit our needs. Luckily making the ribbon (aka toolbar, first introduced in Word 2007) wo…
You need to know the location of the Office templates folder, so that when you create new templates, they are saved to that location, and thus are available for selection when creating new documents.  The steps to find the Templates folder path are …
The viewer will learn how to make their project stand out over others by learning how to change colors and shapes, add spaces, change directions, and add bullets to their charts.
If you’ve ever visited a web page and noticed a cool font that you really liked the look of, but couldn’t figure out which font it was so that you could use it for your own work, then this video is for you! In this Micro Tutorial, you'll learn yo…

632 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question