vba - 集合中的变量引用

标签 vba variables collections nested ref

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

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.ValueCOLL("xr").Value 都输出 2,因为它们都指向到同一个对象。

除非你去做这个:

Set xr = Range("A2")

您刚刚丢弃了一个名为 xr对象指针副本,现在您有 xr 指向 [ A2],并且集合项仍然指向 [A1]。所以当你这样做时:

Range("A2").Value = 3

您不能期望 COLL("xr").Value3,因为它不再是指向同一对象的指针。

集合不可能知道它在索引/键 "xr" 中持有的值需要在您完成后自动开始指向 [A2]重新分配 xr:这不是对象引用的工作方式。

关于vba - 集合中的变量引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48953390/

相关文章:

java - Hibernate 中 CustomCollectionType 与 UserCollectionType 的预期用例是什么?

java - 如何实现实现 Collections 的模板化类

用于隐藏多个工作表中的多个固定离散行的 VBA 代码

Excel VBA : Sort, 然后复制并粘贴

人体高度的 MySQL 变量(tinyint 或 smallint)

c - C中的循环出错了

algorithm - 为工作选择合适的 STL 容器的标准?

mysql - Microsoft Access SQL查询两个表多对一

vba - 在不打开文件的情况下从多个工作簿复制范围

MySQL 变量分区修剪