Solved

VBA Word: Store and retrieve info in a collection

Posted on 2013-11-30
6
448 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
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 14

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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 14

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

The Selection object is designed for user interaction. It has a Range property, so it can be used in most places that a Range object can. Recorded macros must use the Selection because they are simply copying what the user is doing. A Range prope…
Preface: When I started this series, I used the term CommandBars because that is the Office Object class that it discusses. Unfortunately, when Microsoft introduced Office 2007, they replaced the standard Commandbar menus with "The Ribbon" and rem…
In this video, we show how to convert an image-only PDF file into a PDF Searchable Image file, that is, a file with both the image (typically from scanning) and text, which is created in an automated fashion with Optical Character Recognition (OCR) …
This video walks the viewer through the process of creating envelopes and labels, with multiple names and addresses. Navigate to the “Start Mail Merge” button in the Mailings tab: Follow the step-by-step process until asked to find the address doc…

862 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

Need Help in Real-Time?

Connect with top rated Experts

25 Experts available now in Live!

Get 1:1 Help Now