2017-02-01 23 views
1

我还没有找到具体到这个问题的答案,所以希望有人可以为我清除它。将变量设置为新对象时VBA对象是否被破坏?

我明白了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

如果你确实有一个具有'GetObject'方法的dll,你应该在declare语句中将它别名,这样它就不会隐藏VBA'GetObject'函数。 – Comintern

+0

@Comintern:也许我应该使用不同的名称......不,DLL没有GetObject方法,只是一个返回对象的方法。我只用这个名字来保持这个例子简单。 – zaphodalive

回答

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引用计数的方式是相同的。

+0

谢谢,这就是我需要知道的。我想确保我正在处理的电子表格不会创建无数对象,这些对象如果不用'= Nothing'显式地打破变量引用就不会被实例化。 – zaphodalive

+0

FWIW,*所有* COM对象以这种方式处理引用计数,而用户对象是COM对象。 IIR它们扩展VBE7.dll中隐藏的第二个typelib中定义的基类。 VBA使用COM引用计数接口并让COM服务器确定对象的使用寿命。 – Comintern