Миф ошибка out of memory

В этом руководстве объясняется ошибка нехватки памяти VBA.

Ошибка VBA Out of Memory возникает, когда Excel использовал все ресурсы вашего компьютера при выполнении макроса и буквально исчерпывает память для продолжения вычислений или выполнения кода. Это могло произойти, когда у вас запущено много приложений и вы пытаетесь запустить большой макрос в Excel, или, возможно, когда вы создали вечный цикл в Excel по ошибке.

(Дополнительную информацию об ошибках VBA см. В нашем Руководстве по обработке ошибок)

Причины ошибки нехватки памяти

Ошибка нехватки памяти может возникнуть, если вы работаете с книгой, содержащей много листов и тысячи строк. Если мы создадим цикл, который работает с большим объемом данных, может возникнуть ошибка нехватки памяти. Это также может произойти, если мы работаем с несколькими объектами и устанавливаем каждый объект с помощью оператора SET, но затем не очищаем ссылки на объекты между процедурами или циклами.

Например, следующий цикл определенно может вызвать ошибку памяти, если у вас открыто несколько файлов с несколькими листами.

1234567891011121314 Sub TestMemory ()Dim wb As WorkbookDim ws как рабочий листТусклый я как одиночныйДля каждого ББ в Application.WorkbooksДля каждого WS в wb.SheetsСделать до ActiveCell = «A1048576″ActiveCell = 1 + яя = я + 1ActiveCell.Offset (1, 0) .SelectПетляСледующий wsСледующий wbКонец подписки

Предотвращение ошибки нехватки памяти

Объекты выпуска

Если мы работаем с циклами и объектами, нам нужно убедиться, что мы установили для объекта значение НИЧЕГО после того, как он был использован и больше не нужен — это освободит память.

Программирование на VBA | Генератор кода действительно работает для вас!

Убедитесь, что запущен только один экземпляр Excel

Если мы работаем с большими файлами и огромными объемами данных, убедитесь, что у вас не открыто несколько сеансов Excel — его нужно открыть только один раз. Чтобы проверить это, перейдите в диспетчер задач и посмотрите, сколько экземпляров Excel запущено.

Нажмите Ctrl + Alt + Delete на клавиатуре,

Нажмите на Диспетчер задач и убедитесь, что работает только один экземпляр Excel. На рисунке ниже показан один экземпляр с двумя окнами.

Мы также можем проверить в диспетчере задач, что нет экземпляров Excel, работающих в фоновом режиме (т.е. невидимых).

Прокрутите вниз в диспетчере задач, пока не увидите Фоновые процессы и убедитесь, что Excel нет в этом списке программ.

Проверьте размер вашего файла Excel

Часто строки и столбцы, к которым был получен доступ, располагаются ниже тех, которые используются на ваших листах. Excel использует память в этих ячейках, даже если эти ячейки пусты. Проверьте размер файла, нажав CTRL + SHIFT + END на клавиатуре, чтобы увидеть, где находится указатель вашей ячейки. Если он приземляется значительно ниже последней используемой ячейки, убедитесь, что вы удалили все пустые строки и столбцы над указателем ячейки, а затем повторно сохраните файл — это уменьшит размер вашего файла Excel.

Другие способы проверки памяти

Есть несколько других способов освободить память в Excel. Хорошая идея — закрыть Excel, если вы его не используете, а затем открыть его позже — это освободит всю память, которую хранит Excel, поскольку он имеет тенденцию хранить память, даже когда книга не открыта! Всегда проверяйте актуальность вашей версии Office, проверяя наличие обновлений на вашем компьютере и проверяя любые надстройки VBA, которые могут использоваться, но которые вы не используете — вы можете удалить их, чтобы освободить еще больше памяти.

Вы поможете развитию сайта, поделившись страницей с друзьями

Return to VBA Code Examples

In this Article

  • Causes of Out of Memory Error
  • Preventing an Out Of Memory Error
    • Release Objects
    • Make Sure Only one Instance of Excel is Running
    • Check the Size of your Excel file
    • Other ways to Check Memory

This tutorial will explain the VBA Out of Memory Error.

The VBA Out of Memory error occurs when Excel has used all the resources of your machine while running a macro and literally runs out of memory to carry on calculating or running code. This could occur when you have a lot of applications running and try to run a large macro in Excel, or perhaps when you have created a perpetual loop in Excel in error.

(See our Error Handling Guide for more information about VBA Errors)

Causes of Out of Memory Error

An out of memory error can occur if one is working with a workbook that contains many worksheets and thousands of rows. If we create a loop that works with a great volume of data, an out of memory error could occur. It could also occur if we are working with multiple objects and set each object with a SET statement, but then do not clear the references to the objects between procedures or loops.

For example, the following loop could definitely cause a memory error if you have multiple files open with multiple sheets.

Sub TestMemory()
  Dim wb As Workbook
  Dim ws As Worksheet
  Dim i As Single
  For Each wb In Application.Workbooks
    For Each ws In wb.Sheets
      Do Until ActiveCell = "A1048576"
        ActiveCell = 1 + i
        i = i + 1
        ActiveCell.Offset(1, 0).Select
    Loop
  Next ws
 Next wb
End Sub

VBA OutOfMemory Error

Preventing an Out Of Memory Error

Release Objects

If we are working with Loops and Objects, we need to make sure that we set the Object to NOTHING once it has been used and it no longer needed – this will release memory.

VBA OutOfMemory ClearObjectVariable

Make Sure Only one Instance of Excel is Running

If we are working with large files and vast amounts of data, check that you do not have multiple sessions of Excel open – it needs to just be open once.  A way to check this is to go to the Task Manager and see how many instances of Excel are running.

Press Ctl+Alt+Delete on the Keyboard,

Click on Task Manager and make sure that there is only one instance of Excel running.  In the graphic below, there is one instance, with 2 windows.

VBA OutOfMemory TaskManager

We can also check in the Task Manager that there are no instance of Excel running in the background (ie not visible).

Scroll down in the Task Manager until you see Background Processes and make sure Excel is not in that list of programs.

VBA OutOfMemory BackgroundProcesses

Check the Size of your Excel file

Often there are rows and columns that have been accessed below the ones in your worksheets that are actually used.  Excel uses memory in these cells – even if those cells are empty.  Check the size of the file by pressing CTRL+SHIFT+END on the keyboard to see where your cell pointer lands.  If it lands well below the last cell that you are using, make sure you delete all the empty rows and columns above the cell pointer and then re-save the file – this will reduce the size of your Excel file.

Other ways to Check Memory

There are various other ways to free memory in Excel.  A good idea is to close Excel if you are not using it, and then open it later – this will free up any memory that Excel is storing as it tends to store memory even when a workbook is not open!  Always make sure your version of Office is up to date by checking for Updates on your PC and check for any VBA add-ins that may be being used, but that you are not using – you can uninstall these to free up even more memory.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

Home > VBA > VBA Out of Memory Error (Error 7)

puneet-gogia-excel-champs-09-06-23

VBA’s Error 7 (Out of Memory) occurs when your system runs out of resources to back up Excel to execute the macro. When you open an application in your system that takes a part of the resource and when you have to try to execute a macro and the resource that you have is not sufficient, you get the error 7.

Apart from that, there are a few points that you need to check when facing this error (Out of Memory).

  1. As I said, you could have a lot of applications running which makes the system run on the memory. You can close all those applications that are unnecessary.
  2. You have a lot of lengthy codes in the same module. You can try to use different modules for all those codes.
  3. Windows run out of virtual memory.

Below I have shared a few links that can help you to deal with this error.

  • StackOverflow
  • Mr. Excel
  • Clear Memory

What is VBA

  • VBA ERROR Handling
  • VBA Automation Error (Error 440)
  • VBA Error 400
  • VBA Invalid Procedure Call Or Argument Error (Error 5)
  • VBA Object Doesn’t Support this Property or Method Error (Error 438)
  • VBA Object Required Error (Error 424)
  • VBA Overflow Error (Error 6)
  • VBA Runtime Error (Error 1004)
  • VBA Subscript Out of Range Runtime Error (Error 9)
  • VBA Type Mismatch Error (Error 13)

  • Remove From My Forums
  • Question

  • Hi,

    I wrote my own add-in with lot of utilities I need for the daily job, it is not that rocket science, most can be done with the standard Excel features, I just wanted to have it with one mouse click. All at once I was getting the Out of Memory error and rebuild
    the workbook (export & import all modules and forms) and everything looked good but 2 «edits» later I had again the Out of Memory error.

    The (IMO) strange thing is that the add-in is working fine and all options do what is expected.

    Googling to solve this:

    • Limit the number of public variables (done)
    • Release large objects & variants (done)

    I found also some hits about the limits of a vba module (64kB). Some modules are above. Is this really a constraint?

    I am used to include a reference, say Scripting Runtime iso createobject(dictionary). What is the best memory management: a reference or createobject?

    What is best to use: public or property?

    Do you have other advises to get rid of Out of Memory? Thanks.

    • Edited by

      Saturday, April 16, 2016 11:41 AM
      added question

    • Moved by
      Emi ZhangMicrosoft contingent staff
      Monday, April 18, 2016 10:24 AM
      Move case

Answers

  • Try testing in Excel with no other addins and in particular no ComAddins loaded. Rather than unloading them all it might be simpler to start with a ‘clean’ automated instance. Say in Word or with a vbs script start Excel like this

    Dim objXL As Object
    Set objXL = CreateObject("excel.application")
    objXL.Visible = True
    objXL.Workbooks.Add

    You could add another line to open your workbook/addin from file, or open it manually when Excel appears.

    If that makes a difference, your addin’s project doesn’t remain in the explorer when closed and/or now don’t get the «out or memory» message», go through the process of elimination with other addins and ComAddins loaded.

    • Edited by
      Peter Thornton (Excel MVP 2008-13)
      Wednesday, April 27, 2016 9:02 AM
    • Marked as answer by
      JP Ronse
      Wednesday, April 27, 2016 12:10 PM

Out of Memory in VBA

In this article, we will discuss the Out of memory error in VBA with the help of some examples.

Out of memory Error in VBA

VBA gives an Out of memory error when Excel has used all of the resources of our device while running the macro. It will run out the memory to calculate and run the code.

It will occur when many of the programs are running on the device, and we are trying to run the extensive macro in Excel, or maybe we can create a perpetual loop when the error has occurred in Excel.

When someone is working with a workbook containing so many worksheets and many rows, an Out of memory error in VBA occurs. An Out of memory error will happen if we create a loop that will work with a significant amount of data.

If we will work with many objects and set everything with the SET statement, but if we do not clear the references to the objects between loops or procedures. Let’s discuss with the help of an example.

The code is shown below in the loop, which could cause an Out of memory error if we open multiple files with multiple sheets.

Sub TestMemory()
  Dim wb As Workbook
  Dim ws As Worksheet
  Dim i As Single
  For Each wb In Application.Workbooks
    For Each ws In wb.Sheets
      Do Until ActiveCell = "A1048576"
        ActiveCell = 1 + i
        i = i + 1
        ActiveCell.Offset(1, 0).Select
    Loop
  Next ws
Next wb
End Sub

Release Objects in VBA

When working with loops and objects, we have to make sure that we set the object to NOTHING once we use it. We will release memory if it will no longer be needed.

set str = ""
set num = []

We will make sure that only one instance of Excel is running. If we work with enormous files and a large amount of data, we must check that they do not have many sessions open in Excel.

If it is needed, open it once. To check this, we have to go to the Task Manager and check how many instances of Excel are running at that time.

Press Ctrl+Alt+Delete on the keyboard and then click on the Task Manager to ensure that only one instance of Excel is running.

Release Objects In VBA (1)

We can likewise check in the Task Manager that there is no example of Excel running behind the scenes. Look down in the Task Manager until you see Background Processes and ensure Excel isn’t in that frame of mind for projects.

Release Objects In VBA (2)

Check the size of your Excel record. The frequent lines and segments have been gotten to underneath the ones in your worksheets utilized.

Succeed involves memory in these cells — regardless of whether those cells are vacant. Check the size of the document by squeezing CTRL+SHIFT+END on the console to see where your cell pointer lands.

Assuming it lands nicely underneath the last cell that you are utilizing, ensure you erase every one of the unfilled lines and sections over the cell pointer and afterward re-save the record. It will lessen the size of your Excel document.

Alternate Ways to Check the Memory in VBA

There are different alternative ways to free the memory in Excel. The brilliant idea is to close Excel on the off chance that you are not using it and afterward open it later.

It will let loose any memory that Excel is stored, and it tends to hold memory even if the workbook is not opened.

Continuously ensure your version of Office is modern by checking for updates on your device and checking for any VBA add-ins you will be using yet that you are not utilizing. You can uninstall these to let loose significantly more memory.

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Михалков рассказ ошибка читать
  • Мицубиси кольт ошибка 1867
  • Миф если ошибка то
  • Мицубиси аутлендер ошибка p0171
  • Михалков ошибка читать текст

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии