存储在集合中时如何更改Class属性的值
我想将一个类存储在一个Collection中,并且能够更改该类的属性,而不必删除该收集项并将其重新添加回去.
I want to store a class in a Collection and be able to alter the properties of the class without having to remove the collection item and add it back again.
我的研究表明,如果没有删除/替换操作,则无法更改项目本身,但是该项目的属性如何.
My research has shown that the Item itself cannot be changed without the remove/replace operation, but what about the properties of the item.
下面的代码显示了如何执行此操作.运行宏时,调试窗口将同时显示存储对象的初始值和更改后的值.
The code below shows how to do this. When you run the macro, the debug window will show both the initial and the changed values of the stored object.
如果不使用Key
,则需要按其索引号引用收集项.
If you do not use the Key
, you need to reference the collection item by its index number.
Option Explicit
'RENAME cNodes
Private pNode1 As Variant
Private pNode2 As Variant
Public Property Get Node1() As Variant
Node1 = pNode1
End Property
Public Property Let Node1(Value As Variant)
pNode1 = Value
End Property
Public Property Get Node2() As Variant
Node2 = pNode2
End Property
Public Property Let Node2(Value As Variant)
pNode2 = Value
End Property
常规模块
Option Explicit
Sub ChangeCollectionItem()
Dim COL As Collection, cN As cNodes
Dim sKey As String
Dim a, b
Set COL = New Collection
a = 1
b = 2
Set cN = New cNodes
With cN
.Node1 = a
.Node2 = b
sKey = a & "|" & b
COL.Add Key:=sKey, Item:=cN
Debug.Print COL(sKey).Node1, COL(sKey).Node2 '--> 1 2
With COL(sKey)
.Node1 = .Node1 * 10
.Node2 = .Node2 * 5
End With
Debug.Print COL(sKey).Node1, COL(sKey).Node2 '--> 10 10
End With
End Sub