将变量设置为新对象时是否销毁VBA对象?

时间:2017-02-01 21:23:57

标签: excel vba excel-vba object garbage-collection

我没有找到特定于这个问题的答案,所以希望有人可以为我清理它。

我理解VBA垃圾收集器使用引用计数来确定是否不再需要对象,并明确取消关联您使用的变量(从而减少引用计数):

Set objectVariable = Nothing

以下是我现在正在处理的电子表格中的内容:

Declare Function GetObject Lib "ObjectCreator.dll" () As Object
Public MyObject as Object

Sub MyMethod()
    Set MyObject = GetObject()
        ...do stuff with MyObject...

    Set MyObject = GetObject()
        ...do stuff with my new MyObject...

    Set MyObject = GetObject()
        ...do stuff with my even newer MyObject...

    Set MyObject = Nothing
End Sub

我的问题是:所有三个创建的对象是否被GC销毁或只被最后一个销毁?即,当引用变量设置为另一个对象而不是设置为Nothing时,对象的引用计数是否会减少?

1 个答案:

答案 0 :(得分:2)

当您为变量指定对象引用时,引用计数会增加1,当变量通过其他某个赋值丢失引用时,对象的引用计数会减1。例如:

Dim a As Collection
Set a = new Collection 'The reference count of this new Collection object is 1
Set b = a              'The reference count of the Collection object is now 2
Set b = new Collection 'The reference count of the original collection has gone back down to 1 because b is no longer a reference to it, and this new Collection has a reference count of 1

Set a = Nothing        'The original collection no longer has any active references, so VBA safely GCs it.
Set b = Nothing        'The newer collection now no longer has any active references either, so VBA safely GCs it.

现在,在您的情况下,您正在谈论外部DLL,它可以在内部管理自己的内存或运行状态。但是VBA处理COM引用计数的方式是相同的。