Home » excel » vba – how to prevent excel from crashing while running a macro on a large file?

vba – how to prevent excel from crashing while running a macro on a large file?

Posted by: admin May 14, 2020 Leave a comment

Questions:

Good afternoon,

I am running a macro which copies data to another workbook and automatically saves this workbook. The problem is that each line contains a picture, which makes it quite a large file, up to 30mb. Therefore the code takes a while to complete and when I try to run it again, Excel completely freezes and I have to force a shut down on it. When I copy fewer lines, it stays stable. I was wondering if it’s a clipboard issue, but that is not the case. How does it come I can only run it once? Is it a cache issue or something? I am already using compressed pictures and application.screenupdating & enablevents = false.

Thanks in advance

The code below is causing the freeze, basically each picture after row 6 needs to be resized.

    For Each pic In Ws3.Pictures
pic.Select
 If Selection.TopLeftCell.Row > 6 Then
 With Selection
.Height = .TopLeftCell.RowHeight * 0.9
.Width = .Height * PicWtoHRatio
.Top = .TopLeftCell.Top + (.TopLeftCell.RowHeight - .Height) / 2
.Left = .TopLeftCell.Left + (.TopLeftCell.Width - .Width) / 2
End With
End If
Next pic
End Sub

the problem also occurs in a nother part of the code, whenever i try to copy-paste >100 rows excel seems to freeze. i am using cutcopy = False.

How to&Answers:

If you use a loop, you can add DoEvents at the beginning of each iteration. It gives Excel time to handle user events, and not to freeze.

While condition
    DoEvents
    ...
Wend

Answer:

I ran into similar issue when I have 20 pivot table in one file that references 20 different other files and need update. There is no way for me to avoid crash as excel will freeze when it hit around 1.3GB memory usage.

  1. Turn off the auto calculation if you really don’t have any calculation

  2. Within the loop do something like activeworkbook.save each iteration. save the file will help clear out some memory, but since your file is 30MB it might not help a lot to solve the issue.

So you will also need to do:

  1. use a cell to track the last successful iteration so that if your file crash again you can just terminate, and restart from the last successful one. And since you’ve saved the file in every loop then you won’t need to start over

However, if your code will reach the limit in every loop( crash every iteration), then my answer won’t work neither, will need to optimize the code.

Answer:

You may disable the Automatic calculation as well.

Application.Calculation = xlCalculationManual
...
...
...
Application.Calculation = xlCalculationAutomatic

This is could be helpful!

If you are dealing with large Excel files, then you should have powerful hardware and software.

The 64-Bit version of Excel works better with the large files.