如何更改集合项的值 [英] How to change value of an item of a collection

查看:14
本文介绍了如何更改集合项的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用此代码(在 excel-vba 中),我根据数组将多个项目添加到集合中.
我使用数组的值作为键,字符串NULL"作为添加的每个项目的值.

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?

下面是唯一的方法吗?

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

或者是否有类似的东西:(我知道那行不通)

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

Coll("String1") = "myString"

推荐答案

您还可以编写(公共)函数来更新集合.

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.

这篇关于如何更改集合项的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆