使用这段代码(在excel-vba中),我向集合中添加了一些依赖于数组的项。
我使用数组的值作为键,字符串“NULL”作为每个添加项的值。
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
现在,如果我想改变一个项的值,通过键来标识它,我必须删除该项,然后添加一个具有相同键的项,或者可以改变项的值吗?
这下面是唯一的路吗?
Coll.Remove "String1"
Coll.Add "myString", "String1"
或者是这样的:(我知道这行不通)
Coll("String1") = "myString"
7条答案
按热度按时间zu0ti5jz1#
您还可以编写一个(public)函数来更新集合。
您可以通过以下方式调用此函数:
然后您就可以调用一个一行程序。
zysjyyx42#
不能使用
Before
参数来满足这个要求吗?示例:
这不是应该做的工作吗?
2skhul333#
下面是
Coll("String1") = "myString"
***可以***工作的解决方案。当您将对象
.Add
到VBA集合中时,对象本身被添加,而不是它的值。这意味着您可以在对象位于集合中时更改对象的属性。我创建了一个类模块,它将单个变量 Package 在类对象中,并将.Value
作为其默认属性。将此模块保存到.cls
文件,然后在VBA编辑器中保存到File > Import File
。现在,这个版本的代码按您希望的方式工作:
生成结果:
qmelpv7a4#
making a function that deletes the collection item by its key的变体,将其实现为VBA * 属性 *
并像这样使用
如果键不存在,则忽略它,它也可用于添加项
zzoitvuj5#
循环集合并将新值添加到新集合中...
cbjzeqam6#
我刚刚遇到了同样的问题,一个想法,张贴我的解决方案在这里的任何人谁可能需要它。我的解决方案是使一个类名为
EnhancedCollection
,有一个更新功能。保存此代码到一个文件名为EnhancedCollection.cls
,然后导入到您的项目。作为一个额外的好处,您可以随时添加更多的功能。
czq61nw17#