由于Excel未释放内存而导致的“内存不足”错误

时间:2020-01-06 18:24:35

标签: excel vba

我将工作表导入文件,然后以新名称将文件保存在其他位置。

该宏将一直起作用,直到Excel的内存使用量达到3,000MB为止,此时将发生“内存不足”错误。 (此PC上有32GB的内存。)

此行发生错误,Set Wkb3 = Workbooks.Open(filename:=Path & "\" & filename)可能是因为没有足够的内存来打开另一个文件。

Wkb3,即从中导入图纸的源文件,在导入后关闭。

包含导入工作表集合的Wkb2将被保存并在导入完成后关闭。

Wkb1是唯一不断打开的文件。

在崩溃之前,我通常设法进行40次左右的迭代,因此很明显,即使所有的Wkb2和Wkb3都已关闭,Excel的内存中还是有东西。

我尝试在每次导入后保存Wkb2,以查看是否会释放内存。

我尝试将Objects设置为空。

这是我的宏:

Option Explicit
Sub CombineFiles()
Call NewBook 'this marco creates a new file that will hold the imported sheets

Dim Wkb1 As Workbook 'Wkb with Macro
Set Wkb1 = ThisWorkbook

Dim Aname As String
Aname = Wkb1.Sheets(1).Range("A1").Value & "\Master File\Master File.xlsx" 'cell A1 holds the path for each individual folder that holds files that need to be combined

Dim Wkb2 As Workbook 'MasterBook
Set Wkb2 = Workbooks.Open(filename:=Aname)
Dim Wkb3 As Workbook 'DataSource
Dim ws1  As Worksheet 'Wkb with Macro
Set ws1 = Wkb1.Worksheets(1)
Dim ws3  As Worksheet 'DataSource

Dim MyOldName As String
MyOldName = Wkb2.FullName

Dim Path As String
Path = ws1.Range("A1").Value

Dim filename As String
filename = Dir(Path & "\*.xlsx", vbNormal)

Dim Path2 As String
Dim filename2 As String
Path2 = Path & "\Master File\"

Do Until filename = ""
    Set Wkb3 = Workbooks.Open(filename:=Path & "\" & filename)
    For Each ws3 In Wkb3.Worksheets
        ws3.Copy after:=Wkb2.Sheets(Wkb2.Sheets.Count)
    Next ws3
    Wkb3.Close False
    filename = Dir()
Loop

Application.DisplayAlerts = False
filename2 = Wkb2.Worksheets(2).Range("A2").Text
Wkb2.SaveAs filename:=Path & filename & ".xlsx"
Wkb2.Close True
Kill MyOldName
Call KillFiles
Application.DisplayAlerts = True
End Sub

2 个答案:

答案 0 :(得分:0)

不幸的是,我唯一能解决的问题是杀死Excel并通过Windows Task Scheduler重新启动宏。它不能解决“内存不足”错误,但至少它会不时地重新启动宏,因此我不会因为它停留在该错误上而浪费时间。

答案 1 :(得分:-1)

如果您运行的是 Exce32 位,则限制为 4Gb。