You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

64位Office 365中Dictionary内存无法自动释放问题求助

64位Office 365 VBA中Dictionary内存无法自动释放的问题

在64位Office 365的VBA环境中,将数据存入Dictionary后,即便变量超出作用域或被设置为Nothing,内存仍无法自动释放,必须显式调用RemoveAll方法才能释放内存。该问题仅出现在64位版本中,此前使用的32位版本无此异常。

普通Dictionary的内存泄漏情况

示例代码1:

Public Sub testDict()
    Dim dict As Dictionary
    Dim i As Long
    
    Set dict = New Dictionary
    
    For i = 1 To 100000
        dict.Add i, Format(i, "0000000000")
    Next
    
    dict.RemoveAll
    Set dict = Nothing
End Sub

若不调用dict.RemoveAll,Sub执行完毕后内存不会释放,每次重新执行都会占用新的内存空间。

嵌套Dictionary的内存泄漏问题

对于嵌套Dictionary,RemoveAll方法无法有效释放内存:

示例代码2:

Public Sub testNestedDict()
    Dim i As Long
    Dim j As Long
    Dim k As Long
    Dim dict As Dictionary
    
    Set dict = New Dictionary
    
    For i = 1 To 10
        dict.Add i, New Dictionary
    
        For j = 1 To 10
            dict(i).Add j, New Dictionary
        
            For k = 1 To 10
                dict(i)(j).Add k, New Dictionary
            Next
        Next
    Next
    
    dict.RemoveAll
    Set dict = Nothing
End Sub

此代码每次执行会占用约10MB内存,即使编写递归清理函数也无效:

Public Sub testNestedDict()
    Dim i As Long
    Dim j As Long
    Dim k As Long
    Dim dict As Dictionary
    
    Set dict = New Dictionary
    
    For i = 1 To 10
        dict.Add i, New Dictionary
    
        For j = 1 To 10
            dict(i).Add j, New Dictionary
        
            For k = 1 To 10
                dict(i)(j).Add k, New Dictionary
            Next
        Next
    Next
    
    dictErase dict
End Sub

Public Function dictErase(ByRef dict As Dictionary)
    Dim key As Variant
    
    If dict Is Nothing Then
        Exit Function
    End If
    
    For Each key In dict.Keys()
        If TypeOf dict(key) Is Dictionary Then
            dictErase dict(key)
        End If
    Next
    
    dict.RemoveAll
    Set dict = Nothing
End Function

问题范围

该问题似乎不局限于Dictionary,64位VBA中超出作用域的变量内存释放存在异常,与32位版本表现不同。

版本信息

  • 异常版本:Microsoft® Excel® für Microsoft 365 MSO (Version 2408 Build 16.0.17928.20114) 64位
  • 正常版本:Microsoft® Excel® 2019 MSO (16.0.10413.20020) 32位

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 19:07:18