Vba 集合中的变量Ref

Vba 集合中的变量Ref,vba,variables,collections,nested,ref,Vba,Variables,Collections,Nested,Ref,这是我的问题。 我刚刚认识到集合不是其他变量的参考表。看起来添加到集合中的项目不是集合中的引用,但在某种程度上它已“加倍” Sub TestCollection() '-------------------------------------------------------- ' definition Dim COLL As New Collection Dim x As Double Dim xr As Range '------------------------------------

这是我的问题。 我刚刚认识到集合不是其他变量的参考表。看起来添加到集合中的项目不是集合中的引用,但在某种程度上它已“加倍”

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 object集合?

将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$1          $A$1

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

你的措辞很奇怪,但我想我明白你想做什么,你的回答是“不”
x
首先不是一个对象,因此一个不在等式中

xr
是一个对象引用,但当您将其添加到集合中时,所添加的是指向该对象的指针的副本

因此,您有指向
[A1]
xr
,还有一个指向
[A1]
的集合项。如果您这样做:

Range("A1").Value = 2
Range("A2").Value = 3
然后我希望
xr.Value
COLL(“xr”).Value
都输出
2
,因为它们都指向同一个对象

除非你去做这件事:

Set xr = Range("A2")
您刚刚丢弃了名为
xr
的对象指针副本,现在您有了指向
[A2]
xr
,还有一个仍然指向
[A1]
的集合项。所以当你这样做的时候:

Range("A1").Value = 2
Range("A2").Value = 3
您不能期望
COLL(“xr”).Value
3
,因为它不再是指向同一对象的指针


集合不可能知道它在index/key
“xr”
上保存的值需要在分配
xr
后自动开始指向
[A2]
:这不是对象引用的工作方式。

要清楚
xr
是一个范围,
xr=1
没有重新分配
xr
,它的调用
xr.Value=1
仅在
Set xr=Range(“A2”)
时才会更改,与此时添加到集合中的
xr
没有耦合,因为它们是不同的东西
x
在集合中永远不会更改,它是一种值类型,因此总是在赋值时复制。哦,是的,你回答得很好,解释说我所做的只是指针的一个拷贝。但是有办法得到我想要的吗?另一种类型的数据?不是你做什么,而是事情如何运作——不管你做什么,集合总是会有一个对象引用的副本。