这是我的问题。 我刚刚认识到集合不是其他变量的引用表。看起来添加到集合中的项目不是集合中的引用,但它在某种程度上被“加倍”了。
Sub TestCollection()
'--------------------------------------------------------
' definition
Dim COLL As New Collection
Dim x As Double
Dim xr As Range
'--------------------------------------------------------
' Give a value to x and xr
Set xr = Range("A1")
x = 1
xr = 1
'--------------------------------------------------------
' Add to the collection
COLL.Add x, "x"
COLL.Add xr, "xr"
'--------------------------------------------------------
' First debug
Debug.Print "Original value of x and xr (range)"
Debug.Print COLL(1)
Debug.Print COLL(2).Value
'--------------------------------------------------------
' Change the value
x = 2
xr = 2
'--------------------------------------------------------
' Second debug
Debug.Print "Now vba will change x and xr (range)"
Debug.Print COLL(1)
Debug.Print COLL(2).Value
'--------------------------------------------------------
' Change the Ref on xr
x = 3
Set xr = Range("A2")
xr = 3
'--------------------------------------------------------
' Third debug
Debug.Print "Now vba will change x and xr (ref)"
Debug.Print COLL(1)
Debug.Print COLL(2).Value
'--------------------------------------------------------
End Sub
调试打印值:
Original value of x and xr (range)
1
1
Now vba will change x and xr (range)
1
2
Now vba will change x and xr (ref)
1
2
x 和 xr 不是集合中的引用,但它们是不同的对象。
是否有可能拥有我想要的 ref 对象集合?
最佳答案
你的措辞很奇怪,但我想我明白你想做什么,你的回答是“不”。 x
首先不是一个对象,所以一个不在等式中。
xr
是一个对象引用,但是当您将它添加到集合中时,您添加的是指向该对象的指针的副本。
所以你有 xr
指向 [A1]
,还有一个集合项指向 [A1]
。如果你这样做:
Range("A1").Value = 2
然后我希望 xr.Value
和 COLL("xr").Value
都输出 2
,因为它们都指向到同一个对象。
除非你去做这个:
Set xr = Range("A2")
您刚刚丢弃了一个名为 xr
的对象指针副本,现在您有 xr
指向 [ A2]
,并且集合项仍然指向 [A1]
。所以当你这样做时:
Range("A2").Value = 3
您不能期望 COLL("xr").Value
为 3
,因为它不再是指向同一对象的指针。
集合不可能知道它在索引/键 "xr"
中持有的值需要在您完成后自动开始指向 [A2]
重新分配 xr
:这不是对象引用的工作方式。
关于vba - 集合中的变量引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48953390/