从Workbooks.Open causes memory leak分叉
我正在调查以下代码上发生内存泄漏的原因,并发现它在excel不响应时发生。在运行这段代码一段时间后,我看到excel的进程在任务管理器上“未响应”,并且进程开始吞噬内存。
Sub Test01()
Dim fso As FileSystemObject
Set fso = New FileSystemObject
Dim f As File
Dim wb As Workbook
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Dim Files As Variant
Set Files = fso.GetFolder("*****").Files
For Each f In Files
Set wb = Workbooks.Open(f.Path)
wb.Close savechanges:=False
Set wb = Nothing
Next
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
当我在循环中添加DoEvents
时,excel永远不会冻结并且内存使用量会缓慢增加。
For Each f In Files
DoEvents
Set wb = Workbooks.Open(f.Path)
wb.Close savechanges:=False
Set wb = Nothing
Next
为什么当进程冻结时内存使用量会增加?
请注意;
文件夹包含3000个excel文件,因此循环执行了3000次
excel文件的文件大小小于15kb