集合中的变量引用

Variable Ref in collection

这是我的问题。 我刚刚认识到 collection 不是其他变量的引用 table。看起来添加到集合中的项目不是集合中的引用,但它在某种程度上已经 "doubled"。

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 对象集合?

当您将 xr 添加到集合中时 您只是添加了引用的副本 - 之后您对 xr 所做的任何操作都不会影响集合中的副本。

更容易理解:

Dim r1 As Range, r2 As Range

Set r1 = Range("a1")

Set r2 = r1 'make a copy of the reference
Debug.Print r1.Address(), r2.Address()
'>>            $A          $A

Set r2 = Range("a2")
Debug.Print r1.Address(), r2.Address()
'>>            $A          $A

你的措辞很奇怪,但我想我明白你想做什么,你的答案是 "nope"。 x 一开始就不是 object,因此不在等式中。

xr 是一个 object 引用,但是当您将它添加到 collection 时,您添加的是 指向该 object.

因此您有 xr 指向 [A1],还有一个 collection 项目指向 [A1]。如果你这样做:

Range("A1").Value = 2

然后我希望 xr.ValueCOLL("xr").Value 都输出 2,因为它们都指向相同的 object.

除非你去做这个:

Set xr = Range("A2")

您刚刚丢弃了 object 指针 的 副本,名为 xr,现在 xr 指向 [A2],还有一个 collection 项目仍然指向 [A1]。所以当你这样做时:

Range("A2").Value = 3

您不能期望 COLL("xr").Value 成为 3,因为它不再是指向同一个 object 的指针。

collection 不可能知道它保持在 index/key "xr" 的值需要在您 re-assigned xr:这不是 object 引用的工作方式。