VBA:set属性无法设置数组元素

时间:2014-08-30 20:56:34

标签: vba

我有以下代码,我使用nodes数组来保存类中的2个节点对象

主机应用程序:访问2013

'class : cDependenciesTransplant
Dim nodes(0 To 1) As cNode

Property Set OCurNode(node As cNode)
    Set nodes(0) = node
    Set nodes(1) = node
    Set nodes(1) = Nothing

End Property

Property Get OCurNode()
    Set OCurNode = nodes(0)
End Property

'calling code
Public Function StructureDependencies(DepList As cDependenciesList, _
                                  Optional BOB As String = "{", _
                                  Optional EOB As String = "}" _
                                  ) As Boolean

Dim DepTrans As cDependenciesTransplant
Set DepTrans = New cDependenciesTransplant
Set DepTrans.OCurNode = DepList.FirstNode

'FirstNode :
'class: cDependenciesList
Property Get FirstNode() As cNode
    Dim node As cNode
    Set node = New cNode
    Set node.ContList = Me
    Set node.ContDep = Me.pDependency(1)
    node.nNode = 0
    Set FirstNode = node
End Property

当我执行并监控手表时

Set nodes(0) = node

什么都不做,节点(0)仍然只保留,但OCurNode保存对象的引用

Set nodes(0) = node SCRSHT

Set nodes(1) = node

更改节点(0)以保存对象

enter image description here     设置节点(1)=无 将节点(0)和节点(1)更改为空

无论我做什么我都无法改变节点(0) 如果我将数组大小更改为3个单元格作为节点(2) 然后我可以解决节点(1)和节点(2),但仍然节点(0)永远不会改变。

我想我可以通过不使用数组来保存这两个元素来解决它,但我真的很感兴趣,它是VBA中的错误还是我做错了什么?

1 个答案:

答案 0 :(得分:0)

这是因为数组中的所有单元格(0和1)都指向相同的引用。 nodes()数组本质上是一个引用列表 - 全部来自同一个对象。当您将节点(1)设置为等于零时,您将销毁该对象,因此节点(0)也同时设置为空。

您似乎可能希望构建一个指向不同实例的node()数组。如果这就是您所追求的,那么您应该为每个添加的新节点(i = i + 1)增加节点(i)数组。

'Refrain from using Dim in a class
'better to declare this as private
Private nodes(0 To 1) As cNode
Private i             As Integer

Property Set OCurNode(node As cNode)
    If i <= Ubound(nodes) Then
        Set nodes(i) = node
        i=i+1
    End If
End Property