How to change the value of a collection item

With this code (in excel-vba), I add several elements to the collection depending on the array.
I use the value of the array as a key and the string "NULL" as the value for each element added.

Dim Coll As New collection Dim myArr() Set Coll = New collection myArr() = Array("String1", "String2", "String3") For i = LBound(myArr) To UBound(myArr) Coll.Add "NULL", myArr(i) Next i 

Now, if I want to change the value of an element by identifying it with a key, should I delete the element and then add the element with the same key, or can I change the value of the element?

Is this the only way?

 Coll.Remove "String1" Coll.Add "myString", "String1" 

Or there is something like: (I know this does not work)

 Coll("String1") = "myString" 
+5
source share
1 answer

You can also write a (publicly available) function to update the collection.

 public function updateCollectionWithStringValue(coll ax Collection, key as string, value as string) as collection coll.remove key coll.add value, key set updateCollectionWithStringValue = coll end function 

You can call this function:

 set coll = updateCollectionWithStringValue(coll, "String1","myString") 

Then you have one liner to call.

+4
source

All Articles