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

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

问题描述

使用此代码(在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"


推荐答案

Yo您还可以编写一个(公共)函数来对集合进行更新。

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.

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

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