views:

21

answers:

1

I know this is a simple question but it's aggravating me. If I have a key/value pair in a collection but I can't seem to get the value out using the key. I can get the key using the value but not vice versa. Is there some magical way to accomplish this?

For example:

Dim CycleList As Collection
Dim Value as String
Set CycleList = New Collection
CycleList.Add 1, "Some Value"


Value = CycleList(1)

I've also tried CycleList.Item(1) and it's the same result, Value = 1.

+1  A: 

The reason is that you are telling VBA to add an integer 1 with an alternate key of Some Value to the collection. When you call CycleList(1), you are asking for the Item with an index of 1 which happens to be the value 1. The second parameter Some Value represents an alternate key you can use to find the item you want. Here's an example to illustrate:

Public Sub Foo()
    Dim bar As Collection
    Set bar = New Collection
    bar.Add 1, "Blah"
    bar.Add "Foobar"
    bar.Add 99

    Debug.Print "bar(""Blah""): " & bar("Blah")
    Debug.Print "bar(1): " & bar(1)
    Debug.Print "bar(2): " & bar(2)
    Debug.Print "bar(3): " & bar(3)
End Sub

Results when calling Foo in the debug window:

bar("Blah"): 1
bar(1): 1
bar(2): Foobar
bar(3): 99

Note that in the first Debug.Print, I ask for the value by key but in the others, I'm asking for the value by index.

Thomas
You are correct sir! I tried copying someone else's code and assumed that since they used 'index' as a variable name...it was the index for the collection. Mystery solved.
Mikecancook