Excel vba ошибка поддержки безопасных каналов

В этом руководстве объясняется ошибка нехватки памяти 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!

The Excel VBA Out of memory error (Run-time error 7) occurs when Excel runs out of system resources to continue running the macro.

Causes of Out of memory error

Excel can run out of system resources to run macros in the following situations:

  • When we work with a workbook that contains many worksheets and thousands of rows. This error can occur faster when we are using the 32-bit version of Excel that can use only up to a maximum of 2GB of available physical memory on the machine.
  • When we create a loop in Excel VBA that works with a very large dataset. This worsens if we mistakenly created a perpetual loop in the code.
  • When we work with multiple objects that are set with the Set keyword and we do not clear the references to the objects between loops or procedures.
  • This error could happen when we run a macro when we have many other applications running in addition to Excel.
  • When we set a worksheet’s used range that is too large to fit into memory.

It is good practice to clear the memory in Excel VBA after running procedures to ensure optimal system performance.

The following are methods we can use to clear system memory in Excel VBA:

Method 1: Nullify objects when they are no longer needed

If we work with Objects and Loops in our procedures, we need to ensure that the Objects are set to Nothing once the Objects have been used and we no longer need them. We can follow the example below:

Sub nullifyObject()

     Dim largeObject As Object

Set largeObject= Application.Worksheets( «Sheet1»).Range(«A1:D400»)

     ‘loop construct

    Set someLargeObject = Nothing

End Sub

Setting Object variables to Nothing will free up the memory taken up by the Objects.

Method 2: Clear Excel clipboard

If our subroutine copies data from and to ranges, it is good practice that we clear the Excel clipboard before exiting the procedure. This is achieved by placing the Application.CutCopyMode = False statement just before ending the procedure as in the example code below.

Sub clearClipboard()

    Range(«A1:A5»).Select

    Selection.Copy

    Range(«C1»).Select

    ActiveSheet.Paste

    Application.CutCopyMode = False

End Sub

Prevent an Out of memory error

The following are some measures we can take to prevent the Out of memory error in Excel VBA.

Measure 1: Ensure only one instance of Excel is running

Many instances of Excel running at the same time take up more memory resources. The way to check if there are multiple instances of Excel running is by:

  1. Press Ctrl + Alt + Delete on the keyboard to open the Task Manager. In the example below 2 instances of the Excel file are running.

  1. To close the instances we do not need, select that instance and click End Task.

Measure 2: Close all unnecessary applications

If in addition to Excel we have several other programs open, this reduces the amount of memory available to Excel. Closing these other programs can prevent the Out of memory error.

Measure 3: Reduce the size of the Excel file

Sometimes our procedure may be accessing rows and columns that are outside the range that contains data. These empty rows and columns take up memory. We can check for this by pressing Ctrl + Shift + End on the keyboard. If the cell selector lands way below the last cell that has data, then we have to delete all the empty rows and columns that are above the cell selector and save the file. This reduces the size of the Excel file and hence takes up less memory when it is set to an object variable.

Another way of reducing the size of the Excel file is to remove unused sheets, conditional formatting, validation, filtering, and so on.

Measure 4: Uninstall Add-ins that we do not use

Add-ins take up memory. We can uninstall the ones that we do not use.

We use the following steps:

  1. Click on File.

  1. Select Options on the sidebar.

  1. In the Excel Options dialog box select the Add-ins category, select Excel Add-ins or COM Add-ins in the Manage drop-down list, then click Go.

  1. Deselect the Add-ins we want to be uninstalled in the Add-ins available list box and click OK.

Measure 6: Do not use Global variables unless necessary

Whereas procedure-level variables are destroyed at the end of the procedure thus freeing up memory, Global variables remain in memory throughout the runtime of Excel. It is therefore recommended that we do not use Global variables if persistence between procedure calls is not necessary.

Measure 7: Change the structure of the VBA code

If we have lengthy procedures in the same module, we can change the structure of the code such that batches of it occupy different modules.

If our code is using arrays, we can use the Erase function to free the memory of dynamic arrays and reset the values of fixed arrays.

Measure 8: Set Application.ScreenUpdating to False

If we have a macro that is updating the screen constantly when it is not necessary, we can set Application.ScreeenUpdating = False. This will not only speed up the execution of the code but also save on memory usage.

We must remember to set the Application.ScreeenUpdating = True at the end of the macro.

Measure 9: Switch to the 64-bit version of Excel

The 32-bit version of Excel only allows the use of a maximum of 2GB of all the physical memory available to the device. Large excel files that need resources above 2GB will cause an Out of memory error.

If we need to use more than 2GB of memory then we can switch to Excel 64-bit version. This version allows the use of all the available memory available on the machine.

Measure 10: Increase the RAM on the device

Increasing the amount of physical RAM on our device can prevent the Out of memory error. It is important to remember that because of the 2GB limit on Excel 32-bit version, this measure can only have a significant effect on the 64-bit version of Excel.

Conclusion

The Excel VBA Out of memory error (Run-time error 7) occurs when Excel runs out of available system resources to continue running the macro.

In this tutorial we looked at some methods we can use to clear the memory in Excel VBA and several measures we can take to prevent this error.

Post Views: 5,102

I am running VBA code on a large Excel spreadsheet. How do I clear the memory between procedures/calls to prevent an «out of memory» issue occurring?

jordanz's user avatar

jordanz

3694 silver badges12 bronze badges

asked Jan 18, 2013 at 10:32

Marc L's user avatar

6

The best way to help memory to be freed is to nullify large objects:

Sub Whatever()
    Dim someLargeObject as SomeObject

    'expensive computation

    Set someLargeObject = Nothing
End Sub

Also note that global variables remain allocated from one call to another, so if you don’t need persistence you should either not use global variables or nullify them when you don’t need them any longer.

However this won’t help if:

  • you need the object after the procedure (obviously)
  • your object does not fit in memory

Another possibility is to switch to a 64 bit version of Excel which should be able to use more RAM before crashing (32 bits versions are typically limited at around 1.3GB).

answered Jan 18, 2013 at 10:36

assylias's user avatar

assyliasassylias

322k82 gold badges660 silver badges783 bronze badges

5

I’ve found a workaround. At first it seemed it would take up more time, but it actually makes everything work smoother and faster due to less swapping and more memory available. This is not a scientific approach and it needs some testing before it works.

In the code, make Excel save the workbook every now and then. I had to loop through a sheet with 360 000 lines and it choked badly. After every 10 000 I made the code save the workbook and now it works like a charm even on a 32-bit Excel.

If you start Task Manager at the same time you can see the memory utilization go down drastically after each save.

answered Nov 20, 2015 at 14:11

Arne Larsson's user avatar

7

Answer is you can’t explicitly but you should be freeing memory in your routines.

Some tips though to help memory

  • Make sure you set object to null before exiting your routine.
  • Ensure you call Close on objects if they require it.
  • Don’t use global variables unless absolutely necessary

I would recommend checking the memory usage after performing the routine again and again you may have a memory leak.

answered Jan 18, 2013 at 10:39

Dreamwalker's user avatar

DreamwalkerDreamwalker

3,0324 gold badges31 silver badges60 bronze badges

Found this thread looking for a solution to my problem. Mine required a different solution that I figured out that might be of use to others. My macro was deleting rows, shifting up, and copying rows to another worksheet. Memory usage was exploding to several gigs and causing «out of memory» after processing around only 4000 records. What solved it for me?

application.screenupdating = false

Added that at the beginning of my code (be sure to make it true again, at the end)
I knew that would make it run faster, which it did.. but had no idea about the memory thing.

After making this small change the memory usage didn’t exceed 135 mb. Why did that work? No idea really. But it’s worth a shot and might apply to you.

answered Mar 8, 2019 at 6:53

Stevetb77's user avatar

If you operate on a large dataset, it is very possible that arrays will be used.
For me creating a few arrays from 500 000 rows and 30 columns worksheet caused this error. I solved it simply by using the line below to get rid of array which is no longer necessary to me, before creating another one:

Erase vArray

Also if only 2 columns out of 30 are used, it is a good idea to create two 1-column arrays instead of one with 30 columns. It doesn’t affect speed, but there will be a difference in memory usage.

answered Sep 16, 2017 at 1:11

Ryszard Jędraszyk's user avatar

I had a similar problem that I resolved myself…. I think it was partially my code hogging too much memory while too many «big things»

in my application — the workbook goes out and grabs another departments «daily report».. and I extract out all the information our team needs (to minimize mistakes and data entry).

I pull in their sheets directly… but I hate the fact that they use Merged cells… which I get rid of (ie unmerge, then find the resulting blank cells, and fill with the values from above)

I made my problem go away by

a)unmerging only the «used cells» — rather than merely attempting to do entire column… ie finding the last used row in the column, and unmerging only this range (there is literally 1000s of rows on each of the sheet I grab)

b) Knowing that the undo only looks after the last ~16 events… between each «unmerge» — i put 15 events which clear out what is stored in the «undo» to minimize the amount of memory held up (ie go to some cell with data in it.. and copy// paste special value… I was GUESSING that the accumulated sum of 30sheets each with 3 columns worth of data might be taxing memory set as side for undoing

Yes it doesn’t allow for any chance of an Undo… but the entire purpose is to purge the old information and pull in the new time sensitive data for analysis so it wasn’t an issue

Sound corny — but my problem went away

answered Sep 24, 2015 at 17:46

Mike's user avatar

1

I was able to fix this error by simply initializing a variable that was being used later in my program. At the time, I wasn’t using Option Explicit in my class/module.

answered Feb 18, 2020 at 20:16

TechFanDan's user avatar

TechFanDanTechFanDan

3,3396 gold badges46 silver badges89 bronze badges

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.

Понравилась статья? Поделить с друзьями:
  • Excel vba если ошибка то пропустить
  • Excel vba отключить ошибки
  • Excel vba игнорировать ошибку
  • Excel vba игнорирование ошибок
  • Excel exe системная ошибка vcruntime140 dll