Solved

VBA Word: Store and retrieve info in a collection

Posted on 2013-11-30
6
446 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 14

Expert Comment

by:DrTribos
Comment Utility
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
Comment Utility
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
Comment Utility
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

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

A few years ago I was very much a beginner at VBA, and that very much remains the case today.  I'll do my best to explain things as I go in the hope that other beginners can follow.  If you just want to check out a tool that creates a Select Case fu…
This article describes how to use the Send to Mail Recipient command. The instructions apply generally to Office 2007 and later versions, but Microsoft® Word 2013 was used for the specific steps and figures.  What is Send to Mail Recipient? Send…
This video shows and describes the main difference between both orientations in Microsoft Word. Viewers will understand when to use each orientation and how to get the most out of them.
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…

762 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

7 Experts available now in Live!

Get 1:1 Help Now