VBA 和对对象的引用
VBA and references to objects
我对 Set statement 在 VBA 中的工作方式一无所知。
下面是一个测试方法,其中 b 被设置为对 a 对象的引用。然后一个对象被设置为空。
这也应该影响 b 对象,因为它也引用同一个对象。但是尽管如此,b 对象仍然完好无损,可以显示 Collection。这怎么可能?
Private Sub Test()
Dim a As Collection
Dim b As Collection
Set a = New Collection
a.Add "High", "one"
a.Add "Five", "two"
a.Add "!", "three"
Set b = a
Debug.Print a.Item("one") & " " & a.Item("two") & a.Item("three")
Set a = Nothing
Debug.Print b.Item("one") & " " & b.Item("two") & b.Item("three")
Set b = Nothing
End Sub
我认为您的困惑更多是围绕 Set a = Nothing
的作用。
来自 Nothing
文档:
The Nothing keyword is used to disassociate an object variable from an actual object.
...
Several object variables can refer to the same actual object. When Nothing is assigned to an object variable, that variable no longer refers to an actual object.
When several object variables refer to the same object, memory and system resources associated with the object to which the variables refer are released only after all of them have been set to Nothing, either explicitly by using Set, or implicitly after the last object variable referencing the actual object goes out of scope
a
和 b
都引用同一个集合。在 Set a = Nothing
之后,b
仍然引用未更改的集合。
我对 Set statement 在 VBA 中的工作方式一无所知。
下面是一个测试方法,其中 b 被设置为对 a 对象的引用。然后一个对象被设置为空。 这也应该影响 b 对象,因为它也引用同一个对象。但是尽管如此,b 对象仍然完好无损,可以显示 Collection。这怎么可能?
Private Sub Test()
Dim a As Collection
Dim b As Collection
Set a = New Collection
a.Add "High", "one"
a.Add "Five", "two"
a.Add "!", "three"
Set b = a
Debug.Print a.Item("one") & " " & a.Item("two") & a.Item("three")
Set a = Nothing
Debug.Print b.Item("one") & " " & b.Item("two") & b.Item("three")
Set b = Nothing
End Sub
我认为您的困惑更多是围绕 Set a = Nothing
的作用。
来自 Nothing
文档:
The Nothing keyword is used to disassociate an object variable from an actual object.
...
Several object variables can refer to the same actual object. When Nothing is assigned to an object variable, that variable no longer refers to an actual object.
When several object variables refer to the same object, memory and system resources associated with the object to which the variables refer are released only after all of them have been set to Nothing, either explicitly by using Set, or implicitly after the last object variable referencing the actual object goes out of scope
a
和 b
都引用同一个集合。在 Set a = Nothing
之后,b
仍然引用未更改的集合。