清除动态对象实例的内存有时会很慢,有时很快,EXCEL VBA

时间:2017-11-09 07:58:16

标签: excel-vba vba excel

我的EXCEL VBA代码构建了1500多个复杂对象实例,总是具有良好的速度。 处理完所有数据后,我的代码会清理,即所有对象和集合都设置为NOTHING。 有时这种清理很快(~10s),有时很慢(> 5分钟)。

我从不在同一个会话中多次启动此代码,即我总是关闭工作簿(所有工作簿)并确保Excel已关闭。
没有条件格式 屏幕更新设置为FALSE 我使用MS Office Professional Plus 2016。

有没有人知道为什么它有时很快而且有时很慢?

由于某些代码被要求提供superItems集合的上层清理循环:

For idx = 1 To superItems.Count
    Application.statusBar = thisFunction & ": " & superItems.Count - idx & " items left"
    Set superItem = superItems(idx)
    If Not (superItem Is Nothing) Then
        superItem.clear
        Set superItem = Nothing
    End If
    DoEvents
Next idx

Set superItems = Nothing

...这里的方法是superItem.clear: superItem对象包含一个数组(pArrTmxxItems),其中包含指向项目对象的指针。

ub = UBound(pArrTmxxItems)
For idx = 0 To ub
    Set item = pArrTmxxItems(idx)
    If Not (item Is Nothing) Then
        item.clear
        Set item = Nothing
    End If
Next idx

... item.clear看起来像这样: item对象包含CA对象实例的集合pCAs,以及(b)自己类型的集合pChildren(即aChild与item属于同一类)

If Not (pCAs Is Nothing) Then
    For idx = 1 To pCAs.Count
        Set CA = pCAs(idx)
        If Not (CA Is Nothing) Then Set CA = Nothing            'jp171107
    Next idx
    Set pCAs = Nothing                                          'jp171107
End If

If Not (pChildren Is Nothing) Then
    For idx = 1 To pChildren.Count
        Set aChild = pChildren.item(idx)
        aChild.clear
        Set aChild = Nothing
    Next idx
    Set pChildren = Nothing                                     'jp171107
End If

1 个答案:

答案 0 :(得分:0)

  1. 重新声明所有公共变量。它们中的每一个,除常数外。注意范围,不要污染它。

  2. 删除代码的所有部分,将内容设置为空。 VBA环境将为您完成。自动