How to change value of an item of a collection

后端 未结 2 1832
猫巷女王i
猫巷女王i 2020-12-06 17:32

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 eac

相关标签:
2条回答
  • 2020-12-06 17:53

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

    Example:

    Option Explicit
    
    Sub TestProject()
        Dim myStrings As New Collection
    
        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 myStrings
        ' Or with the "Call" keyword: Call PrintCollectionContent(myStrings)
        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 myStrings
        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 myStrings
        Debug.Print "--- End Collection content after removal of the old content ---"
    
    End Sub
    
    Private Sub PrintCollectionContent(ByVal myColl As Variant)
        Dim i as Integer
    
        For i = 1 To myColl.Count()
            Debug.Print myColl.Item(i)
        Next i
    End Sub
    

    Shouldn't this do the job?

    0 讨论(0)
  • 2020-12-06 17:59

    You can also write a (public) function to make updates to a collection.

    public function updateCollectionWithStringValue(coll as 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.

    0 讨论(0)
提交回复
热议问题