How to change value of an item of a collection

China☆狼群 提交于 2019-12-29 01:34:20

问题


With this code (in excel-vba) I add to a collection a number of items depending on an array.
I use the value of the array as key and the string "NULL" as value for each item 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 item, identifying it by the key, I must remove the item and then add an item with same key or is it possible to change the item value?

This below is the only way?

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

Or is there something like: (I know that doesn't work)

Coll("String1") = "myString"

回答1:


You can also write a (public) function to make updates to a 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 invoke this function by:

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

Then you have a one liner to invoke.




回答2:


Can't you use the Before argument to fulfill this requirement?

Example:

Sub TestProject()
    Dim myStrings As New Collection
    Set myStringsRef = myStrings

    myStrings.Add item:="Text 1"
    myStrings.Add item:="Text 2"
    myStrings.Add item:="Text 3"

    ' Print out the content of collection "myStrings"
    Debug.Print "--- Initial collection content ---"
    PrintCollectionContent (myStringsRef)
    Debug.Print "--- End Initial collection content ---"

    ' Now we want to change "Text 2" into "New Text"
    myStrings.Add item:="New Text", Before:=2 ' myStrings will now contain 4 items
    Debug.Print "--- Collection content after adding the new content ---"
    ' Print out the 'in-between' status of collection "myStrings" where we have
    ' both the new string and the string to be replaced still in.
    PrintCollectionContent (myStringsRef)
    Debug.Print "--- End Collection content after adding the new content ---"

    myStrings.Remove 3
    ' Print out the final status of collection "myStrings" where the obsolete 
    ' item is removed
    Debug.Print "--- Collection content after removal of the old content ---"
    PrintCollectionContent (myStringsRef)
    Debug.Print "--- End Collection content after removal of the old content ---"

End Sub

Private Sub PrintCollectionContent(ByVal myColl As Variant)
    For i = 1 To myColl.Count()
        Debug.Print myColl.item(i)
    Next i
End Sub

Shouldn't this do the job?



来源:https://stackoverflow.com/questions/29541710/how-to-change-value-of-an-item-of-a-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!