当variables设置为新对象时,VBA对象是否被销毁?

我还没有find具体的这个问题的答案,所以希望有人可以为我清除它。

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

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 

我的问题是:所有三个创build的对象是被GC还是最后一个破坏? 即当引用variables被设置为另一个对象而不是被设置为Nothing时,对象的引用计数是否减less?

当您将对象引用分配给variables时,引用计数将增加1,并且当variables通过某个其他赋值丢失引用时,对象的引用计数将减less1。 例如:

 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,它可以pipe理自己的内存或内部运行状态不同。 但是VBA处理COM引用计数的方式是一样的。

Interesting Posts