Как ускорить макрос vba excel

Хитрости »

20 Январь 2016              61490 просмотров


Рано или поздно у пишущих на Visual Basic for Applications возникает проблема — код хоть и облегчает жизнь и делает все автоматически, но очень долго. В этой статье я решил собрать несколько простых рекомендаций, которые помогут ускорить работу кода VBA, при этом в некоторых случаях весьма внушительно — в десятки, а то и больше, раз. Основной упор в статье сделан на начинающих, поэтому в начале статьи приводятся самые простые методы оптимизации. Более «глубокие» решения по оптимизации кода приведены в конце статьи, т.к. для применения данных решений необходим достаточный опыт работы в VB и сходу такие методы оптимизации кому-то могут быть непонятны.

  1. Если в коде есть много всяких Activate и Select, тем более в циклах — следует немедленно от них избавиться. Как это сделать я писал в статье: Select и Activate — зачем нужны и нужны ли?
  2. Обязательно на время выполнения кода отключить:
    • автоматический пересчет формул. Чтобы формулы не пересчитывались при каждой манипуляции на листе во время выполнения кода — это может дико тормозить код, если формул много:
      Application.Calculation = xlCalculationManual

      Если во время кода все же нужно пересчитывать какие-то диапазоны, то можно пересчитывать только их:

      Range("A1:C60").Calculate
    • обновление экрана, чтобы действия по изменению значений ячеек и пр. не мелькали. Зачем это надо? Т.к. все эти действия обращаются к графическому процессору и заставляют его трудиться для перерисовки экрана — это может значительно тормозить код:
      Application.ScreenUpdating = False
    • На всякий случай отключаем отслеживание событий. Нужно для того, чтобы Excel не выполнял никаких событийных процедур, которые могут быть в листе, в котором производятся изменения. Как правило это события изменения ячеек, активации листов и пр.:
      Application.EnableEvents = False
    • Если книга выводилась на печать или выводится на печать в процессе выполнения кода, то лучше убрать разбиение на печатные страницы.
      ActiveWorkbook.ActiveSheet.DisplayPageBreaks = False

      если печать производится внутри кода, то эту строку желательно вставить сразу после строки, выводящей лист на печать(при условии, что печать не происходит в цикле. В этом случае — по завершению цикла печати).
      Я советую всегда отключать разбиение на страницы, т.к. это может тормозить весьма значительно, т.к. заставляет при любом изменении на листах обращаться к принтеру и переопределять кол-во и размер печатных страниц. А это порой очень не быстро.

    • На всякий случай можно отключить отображение информации в строке статуса Excel(в каких случаях там вообще отображается информация и зачем можно узнать в статье: Отобразить процесс выполнения). Хоть это и не сильно поедает ресурсы — иногда может все же ускорить работу кода:
      Application.StatusBar = False

    Главное, что следует помнить — все эти свойства необходимо включить обратно после работы кода. Иначе могут быть проблемы с работой внутри Excel. Например, если забыть включить автопересчет формул — большинство формул будут пересчитывать исключительно принудительным методом — после нажатия сочетания клавиш Shift+F9. А если забыть отключить обновление экрана — то есть шанс заблокировать себе возможность работы на листах и книгах. Хотя по умолчанию свойство ScreenUpdating и должно возвращаться в True, если было отключено внутри процедуры — лучше не надеяться на это и привыкать возвращать все свойства на свои места принудительно. По сути все это сведется к нескольким строкам:

    'Возвращаем обновление экрана
    Application.ScreenUpdating = True
    'Возвращаем автопересчет формул
    Application.Calculation = xlCalculationAutomatic
    'Включаем отслеживание событий
    Application.EnableEvents = True

    Как такой код выглядит на практике. Предположим, надо записать в цикле в 10 000 строк значения:

    Sub TestOptimize()
    'отключаем обновление экрана
    Application.ScreenUpdating = False
    'Отключаем автопересчет формул
    Application.Calculation = xlCalculationManual
    'Отключаем отслеживание событий
    Application.EnableEvents = False
    'Отключаем разбиение на печатные страницы
    ActiveWorkbook.ActiveSheet.DisplayPageBreaks = False
     
    'Непосредственно код заполнения ячеек
    Dim lr As Long
    For lr = 1 To 10000
        Cells(lr, 1).Value = lr 'для примера просто пронумеруем строки
    Next
     
    'Возвращаем обновление экрана
    Application.ScreenUpdating = True
    'Возвращаем автопересчет формул
    Application.Calculation = xlCalculationAutomatic
    'Включаем отслеживание событий
    Application.EnableEvents = True
    End Sub

    Разрывы печатных страниц можно не возвращать — они тормозят работу в любом случае.

  3. Следует избегать циклов, вроде Do While для поиска последней ячейки. Часто такую ошибку совершают начинающие. Куда эффективнее и быстрее вычислять последнюю ячейку на всем листе или в конкретном столбце без этого тормозного цикла Do While. Я обычно использую
    lLastRow = Cells(Rows.Count,1).End(xlUp).Row

    другие варианты определения последней ячейки я детально описывал в статье: Как определить последнюю ячейку на листе через VBA?

Для более опытных пользователей VBA я приведу несколько решений по оптимизации кодов в различных ситуациях:

  • Самая хорошая оптимизация кода, если приходится работать с ячейками листа напрямую, обрабатывать их и, возможно, изменять значения, то быстрее все обработки делать в массиве и разом выгружать на листе. Например, код выше по заполнению ячеек номерами будет в этом случае выглядеть так:
    Sub TestOptimize_Array()
    'Непосредственно код заполнения ячеек
    Dim arr, lr As Long
    'запоминаем в массив одним махом все значения 10000 строк первого столбца
    arr = Cells(1, 1).Resize(10000).Value
    'если нужно заполнение для двух и более столбцов
    'arr = Cells(1, 1).Resize(10000, 2).Value
    'или 
    'arr = Range(Cells(1, 1),Cells(10000, 2)).Value
    'или автоматически вычисляем последнюю ячейку и заносим в массив данные, начиная с ячейки А3
    'llastr = Cells(Rows.Count, 1).End(xlUp).Row 'последняя ячейка столбца А
    'arr = Range(Cells(3, 1),Cells(llastr, 2)).Value
    For lr = 1 To 10000
        arr(lr,1) = lr 'заполняем массив порядковыми номерами
    Next
    'Выгружаем обработанный массив обратно на лист в те же ячейки
    Cells(1, 1).Resize(10000).Value = arr
    End Sub

    Но здесь следует учитывать и тот момент, что большие массивы могут просто вызвать переполнение памяти. Наиболее актуально это для 32-битных систем, где на VBA и Excel выделяется памяти меньше, чем в 64-битных системах

  • Если используете быстрый ЕСЛИ — IIF, то замените его на IF … Then … Else
  • Так же лучше вместо Switch() и Choose() применить тот же IF … Then … Else
  • В большинстве случаев проверять строку на «не пусто» лучше через Len(), чем прямое сравнение с пустотой: Len(s)=0 вместо s = «». Связано с тем, что работа со строками значительно медленнее, чем с числовыми данными и Len по сути не подсчитывает длину переменной, а берет это число непосредственно уже готовое из памяти. При сравнении же текста с пустой строкой(«»), VBA сначала создает в памяти переменную нулевой длинны, а уже потом сравнивает с ней наш текст. Поэтому в некоторых случаях так же ускоряет сравнение и в таком виде: s = vbNullString
  • Не применять объединение строк без необходимости. Например, s = «АВ», будет быстрее, чем: s =»А» & «В»
  • Не применять сравнение текстовых величин напрямую. Лучше применить встроенную функцию StrComp:
    If s <> s1 Then будет медленнее, чем
    If StrComp(s, s1, vbBinaryCompare) <> 0
    и тем более, если при сравнении необходимо не учитывать регистр:
    If LCase(s) <> LCase(s1) Then будет медленнее, чем
    If StrComp(s, s1, vbTextCompare) <> 0
  • Циклы For … Next в большинстве случаев работает быстрее, чем цикл Do … Lоор
  • Избегать присвоения переменным типа Variant. Хоть соблазн и велик — этот тип забирает много памяти и в дальнейшем замедляет работу кода. Так же для объектных переменных следует избегать по возможности безликого глобального типа Object и применять конкретный тип:
    Dim rRange as Object, wsSh as Object

    будет медленнее работать, чем:

    Dim rRange as Range, wsSh as Worksheet

    Причина в том, что при объявлении As Object мы не даем VBA практически никакой информации о типе данных, кроме того, что это какой-то объект. И VBA приходится «на лету» внутри кода при каждом обращении к такой переменной определять её конкретный тип(Range, Worksheet, Workbook, Chart и т.д.). Что опять же занимает время.

  • Если работаете с массивами, то можно при объявлении указать это явно:

    вместо

    Такая инициализация происходит быстрее.
    А еще лучше будет при этом еще и тип данных сразу присвоить:

    Dim arr() as string, arr2() as long

    но это только если есть уверенность в том, что в массив будут заноситься строго указанные типы данных

Конечно, это не все приемы и решения для оптимизации. Но на первых парах должно хватить. Плюс, всегда следует исходить из здравого смысла. Например, если код выполняется за 2 секунды, то вероятно нет смысла его дальше оптимизировать. Конечно, если этот код не из тех, которые просто изменяют значение одной-двух ячеек.


Статья помогла? Поделись ссылкой с друзьями!

  Плейлист   Видеоуроки


Поиск по меткам



Access
apple watch
Multex
Power Query и Power BI
VBA управление кодами
Бесплатные надстройки
Дата и время
Записки
ИП
Надстройки
Печать
Политика Конфиденциальности
Почта
Программы
Работа с приложениями
Разработка приложений
Росстат
Тренинги и вебинары
Финансовые
Форматирование
Функции Excel
акции MulTEx
ссылки
статистика

As part of our work to help enterprises upgrade to Office 365 ProPlus, we have found that some users have been experiencing slow running VBA, which can be frustrating. The good news is that there are steps which can be taken to improve performance.

This post aims to raise awareness of the steps that you can take to improve the performance of your macros, whether you are an end user, IT admin, or developer. We’ve collected the following steps from blog posts, Microsoft field engineers, and Microsoft MVPs like Charles Williams and Jan Karel Pieterse.

1. Turn off everything but the essentials in VBA

One of the first things to do when speeding up VBA code is to turn off unnecessary features such as animations, screen updating, automatic calculations and events while your macro is running. These features can add extra overhead and slow down the macro, particularly if the macro is modifying many cells and triggering lots of screen updates and recalculations.

The below code sample shows you how to enable/disable:

  • Manual calculations
  • Screen updates
  • Animations
Option Explicit
Dim lCalcSave As Long
Dim bScreenUpdate As Boolean
Sub SwitchOff(bSwitchOff As Boolean)
  Dim ws As Worksheet
    
  With Application
    If bSwitchOff Then 

      ' OFF 
      lCalcSave = .Calculation
	bScreenUpdate = .ScreenUpdating
      .Calculation = xlCalculationManual
      .ScreenUpdating = False
      .EnableAnimations = False
      
      '
      ' switch off display pagebreaks for all worksheets
      '
      For Each ws In ActiveWorkbook.Worksheets
        ws.DisplayPageBreaks = False
      Next ws
    Else
 
      ' ON
      If .Calculation <> lCalcSave And lCalcSave <> 0 Then .Calculation = lCalcSave
      .ScreenUpdating = bScreenUpdate
      .EnableAnimations = True
      
    End If
  End With
End Sub

Sub Main()
  SwitchOff(True) ‘ turn off these features
  MyFunction() ‘ do your processing here
  SwitchOff(False) ‘ turn these features back on
End Sub

2. Disabling Office animations through system settings

Animations can be disabled across Windows by accessing the Ease of Access Center.

Animations can be disabled in Excel specifically, under the Advanced or Ease of Access tab, within the File > Options menu.

Please see the following link for more information: https://support.office.com/en-us/article/turn-off-office-animations-9ee5c4d2-d144-4fd2-b670-22cef9fa…

3. Disabling Office animations through registry settings

Office animations can be disabled across multiple computers by setting the appropriate registry key via a group policy setting.

HIVE: HKEY_CURRENT_USER
Key Path: SoftwareMicrosoftOffice16.0CommonGraphics
Key Name: DisableAnimations
Value type: REG_DWORD
Value data: 0x00000001 (1)

Warning: Using Registry Editor incorrectly can cause serious, system-wide problems that may require you to re-install Windows to correct them. Microsoft cannot guarantee that any problems resulting from the use of Registry Editor can be solved. Use this tool at your own risk.

4. Removing unnecessary selects

The select method is common to see in VBA code, however it is often added to the macro where it isn’t needed. Select can trigger cell events such as animations and conditional formatting which slow the macro down, so removing unnecessary selects can significantly speed up your macro.

The following example shows the code before and after making the change to remove unnecessary selects.

Before

Sheets("Order Details").Select
Columns("AC:AH").Select
Selection.ClearContents

After

Sheets("Order Details").Columns("AC:AH").ClearContents

5. Using the With statement to read object properties

When working with objects, use the With statement to reduce the number of times object properties are read. The following example shows the code before and after making the change to use the With statement.

Before

Range("A1").Value = “Hello”
Range("A1").Font.Name = “Calibri”
Range("A1").Font.Bold = True
Range("A1").HorizontalAlignment = xlCenter

After

With Range("A1")
  .Value2 = “Hello” 
  .HorizontalAlignment = xlCenter
    With .Font
      .Name = “Calibri”
      .Bold = True
    End With
End With

6. Using ranges and arrays

Reading and writing to cells in Excel from VBA is expensive. There is an overhead that is incurred every time data moves between VBA and Excel.

The mountain between Excel and VBAThe mountain between Excel and VBA

This means that you should try to reduce the number of times you pass data between VBA and Excel. This is where ranges are useful. Instead of reading and writing to each cell individually in a loop, read the entire range into an array at the start, loop through the array, and then write the entire array back at the end. The following example code shows how a range can be used to read and write the values once, instead of reading each cell individually.

Dim vArray As Variant
Dim iRow As Integer
Dim iCol As Integer
Dim dValue As Double
vArray = Range("A1:C10000").Value2 ‘ read all the values at once from the Excel cells, put into an array 

For iRow = LBound(vArray, 1) To UBound(vArray, 1)
  For iCol = LBound(vArray, 2) To UBound(vArray, 2)
    dValue = vArray (iRow, iCol)
    If dValue > 0 Then 
      dValue=dValue*dValue ‘ Change the values in the array, not the cells 
    vArray(iRow, iCol) = dValue
  End If
Next iCol
Next iRow
Range("A1:C10000").Value2 = vArray ‘ writes all the results back to the range at once

7. Use .Value2 instead of .Text or .Value

There are different ways that you can retrieve values from a cell, and which property you use can make a different in the performance of your code.

.Text is commonly used to retrieve the value of a cell – it returns the formatted value of a cell. Getting the formatting of a cell is more complex than just retrieving a value, and makes .Text quite slow.

.Value is an improvement over .Text, as this mostly gets the value from the cell, without formatting. However for cells formatted as a date or currency, .Value will return a VBA date or VBA currency (which may truncate decimal places).

.Value2 gives the underlying value of the cell. As it involves no formatting, .Value2 is faster than .Value. .Value2 is faster than .Value when processing numbers (there is no significant difference with text), and is much faster using a variant array.

For a more detailed explanation, please see Charles William’s blog post, “TEXT vs VALUE vs VALUE2”: https://fastexcel.wordpress.com/2011/11/30/text-vs-value-vs-value2-slow-text-and-how-to-avoid-it/

8. Bypass the clipboard (copy and paste)

When you use the Macro Recorder to record operations that use copy and paste, the code will use the copy and paste methods by default. However, within VBA code, it is much faster to bypass the clipboard and use internal operations instead. By default, copying will copy everything, including formulas, values and formatting. You can make copying faster by only copying values or formulas, without the formatting. The following example shows the code before and after making the change to bypass the clipboard.

Before

Range("A1").Select
Selection.Copy
Range("A2").Select
ActiveSheet.Paste

After

‘ Approach 1: copy everything (formulas, values and formatting
Range("A1").Copy Destination:=Range("A2")

‘ Approach 2: copy values only
Range("A2").Value2 = Range("A1").Value2

‘ Approach 3: copy formulas only
Range("A2").Formula = Range("A1").Formula

If you still find that a macro takes longer than expected to execute many individual copy and paste operations, you may want to apply the following hot fix: https://support.microsoft.com/en-in/help/2817672/macro-takes-longer-than-expected-to-execute-many-in…

9. Use Option Explicit to catch undeclared variables

Option Explicit is one of the available Module directives in VBA that instructs VBA how to treat the code within the code module. Setting Option Explicit requires all variables to be declared and will give compile errors if an undeclared variable is used. This helps catch incorrectly typed variable names and improves performance with all variable types being defined at compile time, instead of being inferred at runtime.

This can be set by typing: Option Explicit at the top of each module in your project or by checking the «Require Variable Declaration» option under Tools -> Options in the VBA editor. 

Additional Details on Module directives can be found here: https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/option-explicit-s…

Conclusion

We hope that this has helped highlight some of the ways that you can make your macros run faster. We’re sure that we haven’t covered everything, so please comment below with any other tips or tricks to improve the performance of your macros in Excel.

Further reading

https://blogs.office.com/en-us/2009/03/12/excel-vba-performance-coding-best-practices/

http://datapigtechnologies.com/blog/index.php/ten-things-you-can-do-to-speed-up-your-excel-vba-code/

https://www.ozgrid.com/VBA/SpeedingUpVBACode.htm

FAQs:

After using the new macro animations stopped working/it’s stuck on manual calculation.

It is possible the code disables the various settings, but the macro crashes before re-enabling these settings. To fix this, you will need to run the code to enable these settings again.

Other resources

https://www.thespreadsheetguru.com/blog/2015/2/25/best-way-to-improve-vba-macro-performance-and-prev… — The Best Way To Improve VBA Macro Performance And Prevent Slow Code Execution

https://www.ozgrid.com/VBA/SpeedingUpVBACode.htm — Optimize Slow VBA Code. Speeding Up Slow Excel VBA Code

About the co-authors

Charles Williams founded Decision Models in 1996 to provide advanced consultancy, decision support solutions, and tools based on Microsoft Excel and relational databases. Charles is the author of FastExcel, the widely used Excel performance profiler and performance toolset, and co-author of Name Manager, the popular utility for managing defined names. For more information about Excel calculation performance and methods, memory usage, and VBA user-defined functions, visit the Decision Models Web site.

Jan Karel Pieterse is a long time Excel MVP who develops custom solutions focused on Microsoft Office, with deep expertise in Excel and VBA. He runs the website JKP Application Development Services site, where you can find an interesting collection of articles, training events, and utilities. For a good overview of topics, see this list of in-depth articles. Jan develops some cool and useful utilities for Excel, including NameManager, RefTreeAnalyser, and Flexfind. You can find a full list on the downloads page.

Если вы хотите, чтобы ваш код макроса VBA работал быстро, то необходимо отключить некоторые функции VBA Excel в начале кода. После выполнения макроса снова включаем все функции.
Для этого мы можно использовать следующий код:

' Процедура : TurnOffFunctionality
' Источник  : www.planacademy.ru
' Назначение: Отключает автоматические вычисления, обработку событий и обновление экрана
Public Sub TurnOffFunctionality()
    ' Все расчеты переводим в ручной режим
    Application.Calculation = xlCalculationManual
    ' Отключаем статусную строку
    Application.DisplayStatusBar = False
    ' Отключаем события
    Application.EnableEvents = False
    '  Отключаем показ разбиения листа на печатные страницы 
    If Workbooks.Count Then
      ActiveWorkbook.ActiveSheet.DisplayPageBreaks = False 
    End If
    ' Больше не обновляем страницы после каждого действия  
    Application.ScreenUpdating = False
    ' Отключаем сообщения Excel
    Application.DisplayAlerts = False 
End Sub

' Процедура : TurnOnFunctionality
' Источник  : www.planacademy.ru
' Purpose   :  Включает автоматические вычисления, обработку событий и обновление экрана 
Public Sub TurnOnFunctionality()
    Application.Calculation = xlCalculationAutomatic
    Application.DisplayStatusBar = True
    Application.EnableEvents = True
     If Workbooks.Count Then
      ActiveWorkbook.ActiveSheet.DisplayPageBreaks =  True 
    End If 
    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
End Sub

Использовать эти процедуры можно следующим образом:

Sub Main()

    ' Выключить вначале
    TurnOffFunctionality
    
    ' Ваш основной код здесь
    
    ' Включить в конце
    TurnOnFunctionality

End Sub

Иногда, когда выполняется макрос, процедура не доходит до строки включения функций “TurnOnFunctionality”. Это может произойти из-за ошибки или из принудительной остановки кода в определенный момент. Если это произойдет, вы можете снова включить все функции, выбрав процедуру TurnOnFunctionality в окне радактирования кода и нажав клавишу F5.

Никогда не используем функцию Select

При копировании данных в Excel VBA не используйте метод Select-никогда! Большая ошибка, которую делают новички VBA, – это думают, что им нужно выбрать ячейку или диапазон, прежде чем ее скопируют.
Например:

shRead.Activate
shRead.Range("A1").Select
shWrite.Activate
Selection.Copy Activate.Range("H1")

Помните об этих двух важных вещах, прежде чем используется VBA для копирования данных:

  • Вам не нужно выбирать ячейку или диапазон ячеек.
  • Вам не нужно выбирать или активировать рабочий лист.

Часто можно увидеть, что Select используется во многих примерах в интернете. Но вам не нужно использовать его для копирования ячеек – никогда!

Общие рекомендации

Оптимизация
1) Желательно избегать формул массивов (по возможности)
2) Избегать волатильных формул (по возможности) (условное форматирование, как пример волатильности)
3) Использовать структурированные таблицы и именованные диапазоны
4) Заменять неиспользуемые формулы значениями
5) Хранить все данные для расчета на одном листе (по возможности)
6) Избегать в формулах ссылки на целые столбцы
7) использовать =IFERROR вместо IF + ISERR/ISERROR
8) использовать MAX(A1;0) вместо IF(A1>0;A1;0)
9) использовать INDEX+MATCH вместо VLOOKUP
10) использовать — для конвертации лог.значение в 0/1
11) использовать A1*0.1 чем A1/10
VBA
12) Использовать оператор if else, вместо IIF
13) Использовать Long т.е. Long лучше Вуte, Integer, конечно, variant
14) Применять if else, чем switsh; shoose
15) Лучше проверять строку так len(s)=0, чем s = “”
16) Лучше инициализировать строку так s =vbnullstring, чем s =””
17) Если возможно писать так s = “АВ”, чем s =”А” & “В”
18) Вставлять строку в текст так Мid$(а,3,4)=”like”. чем s = left$(8,2) & “like” & mid(з,7)
19) Сравнивать строки так if strcomp(s1,s2,vbtextcompare) =0, чем if ucase(s1)=ucase(s2)
20) Лучше использовать $-функцию, т.е. left$ лучше left.
21) Цикл for …next. работает быстрее do…lоор
22) Точнее объявлять объекты: as commandbutton лучше as control, еще лучше as object
23) Цикл for Еасh..next лучше, чем цикл for…next семейств объектов
24) Цикл for …next лучше, чем цикл fог Еасh…next: для массивов.
25) Использовать оператор With при обращении к элементам сходной иерархической модели
Для общих (расшаренных) книг
26) Удалять пользовательские представления Вид-Представления-Удалить
27) Снять пометки с Параметров печати и Фильтров , так Рецензирование-Доступ к книге-Параметры печати и Фильтры
28) Периодически отключать общий доступ, сохранять книгу, отключать общий доступ и снова сохранять
29) Удостовериться, что книга открывается в режиме просмотра Вид-Обычный (для того, чтобы избежать обращения к сетевому принтеру с соответствующими временными последствиями)
30) Перелить одну книгу в другую путем копирования не листа, а содержимого в новую книгу со вставкой сначала значения, потом формулы, потом форматы и макросы через импорт экспорт перенести в новую книгу
31 ) Удалить избыточное форматирование

To achieve the best VBA code performance after compilation with DoneEx VbaCompiler for Excel, we recommend to apply all of the following tips to optimize VBA code performance before compilation.

1. Turn off “Automatic Calculation” mode and enable “Manual Calculation” mode

The Application.Calculation property allows you to control Excel’s calculation mode from your VBA code.

Automatic (xlCalculationAutomatic) mode is the default value of Application.Calculation property and it means that Excel controls the calculation and decides when to trigger the calculation of the workbook (e.g. when a new formula is entered, a cell value is changed, or the value of the Range object is changed from VBA code).

Manual (xlCalculationManual) mode means Excel waits for the user action (or action from your VBA code) to explicitly begin calculation.
Since recalculating a workbook takes time and resources, then to increase the VBA code calculation performance it is better to set the Application.Calculation property to manual mode.

Turn off the automatic calculation mode while your VBA code is running, and then set the mode back when it’s done to increase the VBA performance.

Example:

Dim savedCalcMode As XlCalculation
savedCalcMode = Application.Calculation
Application.Calculation = xlCalculationManual
< ... your code here ... >
Application.Calculation = savedCalcMode

2. Turn off “Screen Updating”

The Excel Application.ScreenUpdating property controls the re-drawing of the Excel screen’s visible parts. The Excel spends some resources to draw the screen during re-calculation. You will get noticeable performance improvements by switching off the Application.ScreenUpdating property by setting it to False.

Example:

Dim savedScreenUpdating as Boolean
savedScreenUpdating = Application.ScreenUpdating
Application.ScreenUpdating = False
< ... your code here ... >
Application.ScreenUpdating = savedScreenUpdating

3. Disable Application.EnableEvents

In most cases you do not want to allow the Excel to process events while the VBA code is running because it slows calculation.

Example:

Dim savedEnableEvents as Boolean
savedEnableEvents = Application.EnableEvents
Application.EnableEvents = False
< ... your code here ... >
Application.EnableEvents = savedEnableEvents

4. Turn off ActiveSheet.DisplayPageBreaks

Another way to speed up your VBA code is by disabling the ActiveSheet.DisplayPageBreaks property.

Example:

Dim savedPageBrakes as Boolean
savedPageBrakes = ActiveSheet. DisplayPageBreaks
ActiveSheet. DisplayPageBreaks = False
< ... your code here ... >
ActiveSheet. DisplayPageBreaks = savedPageBrakes

5. Disable animation in Excel by “Application.EnableAnimations = False”

Animations are enabled for user actions and representations, beautifying Excel. Disabling these animations allows for the improvement of VBA performance.

Example:

Dim savedEnableAnimations as Boolean
savedEnableAnimations = Application.EnableAnimations
Application.EnableAnimations = False
< ... your code here ... >
Application.EnableAnimations = savedEnableAnimations

6. Turn off status bar by “Application.DisplayStatusBar = False”

Disabling the status bar frees up resources for VBA calculation and improves VBA calculation performance.

Example:

Dim savedStatusBar as Boolean
savedStatusBar = Application.DisplayStatusBar
Application.DisplayStatusBar = False
< ... your code here ... >
Application.DisplayStatusBar = savedStatusBar

7. Turn off “Print Communication”

Disabling Application.PrintCommunication property also speeds up VBA execution.

Example:

Dim savedPrintCommunication as Boolean
savedPrintCommunication = Application.PrintCommunication
Application.PrintCommunication = False
< ... your code here ... >
Application.PrintCommunication = savedPrintCommunication

8. Use OptimizedMode() procedure to enable optimization

The best way to use the actions from the tips above is to combine them all into one procedure which allows you to enable an optimized VBA calculation mode with a single call before executing your VBA code and disabling it all with one call after that.

Here you may find the full OptimizedMode procedure definition.

Public Sub OptimizedMode(ByVal enable As Boolean)
     Application.EnableEvents = Not enable
     Application.Calculation = IIf(enable, xlCalculationManual, xlCalculationAutomatic)
     Application.ScreenUpdating = Not enable
     Application.EnableAnimations = Not enable
     Application.DisplayStatusBar = Not enable
     Application.PrintCommunication = Not enable
End Sub

Usage Example:

OptimizedMode True
< ... your code here ... >
OptimizedMode False

9. Avoid selecting and activating methods

Select and Activate methods are slow methods and add a time overhead during calculation.

For example:
Instead of using ‘Select’ method and ‘Selection’ object, like:

ActiveSheet.Select
Selection.Range("A1").Value2 = "text"

Use direct access to the object without unnecessary selection:

ActiveSheet.Range("A1").Value2 = "text"

10. Avoid recording macro

VBA code generated from macro recording has low performance efficiency because it uses a lot of Select and Selection methods.

11. Avoid unnecessary Copy/Paste operations

Copy/Paste operations may seem appropriate for many algorithm situations, but it is very ineffective for VBA code performance.

Instead of the code:

Worksheets("Sheet1").Range("A1:H10").Copy
Worksheets("Sheet2").Range("A1").PasteSpecial

Use the following code:

Sheet2.Range("A1:H10").Value2 = Sheet1.Range("A1:H10").Value2

12. Use “ForEach” loop instead of “indexed For” loop for collections

When a collection object is traversed in an indexed For loop, each item in the collection is accessed through an index operation, which is much slower than traversing each object in the collection one-by-one in the ‘For Each’ loop.

Instead of code like:

For i=1 to Collection.Count
    Collection.Item(i).Value = value
Next 

Use following approach:

For Each obj in Collection
    Obj.Value = value
Next

13. Use “With … End” statement

Use the With…End statement instead of full qualified access to the object’s methods or data.

Instead of:

ThisWorkbook.Worksheets("Sheet1").Range("A1").Font.Bold = True
ThisWorkbook.Worksheets("Sheet1").Range("A1").Value2 = 100

Use the following code:

With ThisWorkbook.Worksheets("Sheet1").Range("A1")
    .Font.Bold = True
    .Value = 100
End With

14. Use simple objects rather than compound objects

For the same reason as in the previous advice, you can reduce the time overhead for accessing the qualified object’s method by assigning a complex qualified name to a separate object and use that object for accessing the object’s methods.

Instead of:

ThisWorkbook.Worksheets("Sheet1").Range("A1").Font.Bold = True
ThisWorkbook.Worksheets("Sheet1").Range("A1").Value2 = 100

Use the following code:

Dim rng as Range
Set rng = ThisWorkbook.Worksheets("Sheet1").Range("A1")
Rng.Font.Bold = True
Rng.Value2 = 100

15. Use vbNullString instead of an empty string

Technically vbNullString is not a string – it is a constant declared as a Null pointer. When you use vbNullString instead of empty string (“”) you avoid some extra memory allocations which give time overheads.

Instead of assignment like this:

 Dim Str as String
 Str = ""

Use this:

 Dim Str as String
 Str = vbNullString

16. Use “Early Binding” instead of “Late Binding”

Binding is a process of coupling the object variable with its content. After the binding, the variable represents the object and allows it to get access to the methods and data of the object.
For detailed explanation of the difference between ‘Early binding’ and ‘Late Binding’ please read the following articles:
Early vs. Late Binding
Using early binding and late binding in Automation

Example of “Late binding”:

Dim obj as Object
Set obj = CreateObject("Excel.Application")

Example of “Early Binding”:

Dim xlApp as Excel.Application
Set xlApp = New Excel.Application

17. Avoid using Variant type

Variant type is a dynamic type – that means Variant variables can accept any other type of data and store it. Usage of the Variant type may be comfortable and time saving for programming time, but it sacrifices time overhead during run-time (when your code is working) because conversion from exact type to Variant and from Variant to any other type is time consuming.
For example: If the data has a ‘String’ type it should be stored into the variable which is declared with a String type but not into a Variant type variable, also it makes sense for all other types.

Also avoid declaration like:

 Dim v

The variable ‘v’ in code line above is declared as Variant because declaration of type is missed.

 Dim a, b, c as Long

In this code example only the ‘c’ variable is declared as Long, but ‘a’ and ‘b’ are declared as Variant.
To declare all variables in one line you need to point out the exact type for each variable declaration, like so:

 Dim a as Long, b as Long, c as Long

18. Avoid declaration of method parameters without type

Instead of:

Private Sub Proc1(a,b,c)

Use exact type declaration for each parameter:

Private Sub Proc1(ByVal a as Long, ByVal b as String, ByVal c as Integer)

19. Use ‘Option Explicit’

If you miss the variable declaration it will be assumed by VBA as variable with Variant type.

Following to the previous tip it is better to avoid Variant typed declarations if you want to maximize your VBA code performance.

By default, the VBA do not warn you that variable is not declared. To avoid this situation, use the ‘Option Explicit’ statement in the first line of each VBA module in your VBA project.

With the ‘Option Explicit’ statement, VBA will warn about any undeclared variable.

Optimize VBA code tip - Option Explicit directive allows to detect undeclared variables

20. Avoid using Object type, use specific object type declarations

When you use the Object type, VBA does not know what exact type object it contains and will resolve this during run-time (when your code is working) which will take additional time. To avoid this overhead time, you need to use the exact type of variable for declaration.

Instead of code:

Dim obj as Object
Set obj = New Collection

Use following code:

Dim oCollection as Collection
Set oCollection = New Collection

21. Use “Const” for constant declarations

Declare constant instead of variable if you need to have a constant.

Use constant declaration:

Const pi as Double = 3.14159265359

Instead of following:

Dim pi as Double
Pi = 3.14159265359

22. Use ByVal modifiers for parameters

When you do not need to return value from the method parameter then explicitly declare this parameter as ByVal.

Use this:

Private Sub Proc1(ByVal a as Long)

Instead of:

Private Sub Proc1(a as Long)

23. Move out unnecessary actions from a loop body

Each unnecessary action inside a loop will be repeated and it will accumulate overhead time for algorithm. By removing such pieces of code from loop body you optimize VBA code.

For example, instead of the following code:

Dim rng as Range
For Each rng in Worksheets("Sheet1").Range("A1:AA100")
    Dim result as Range
    Set result = Worksheets("Sheet2").Range("A1")
    result.Value2 = result.Value2 + rng.Value2
Next

Use this code:

Dim result As Double
Dim rng As Range
For Each rng In Worksheets("Sheet1").Range("A1:AA100")
    result = result + CDbl(rng.Value2)
Next
Worksheets("Sheet3").Range("A1").Value2 = result

24. Use String versions of built-in functions instead of the Variant version

If you are working with VBA string functions, it is better to use String typed version functions – which have a ‘$’ dollar sign in the suffix instead of the Variant typed version of the same functions.

Instead of these functions:

Chr(), ChrB(), ChrW(), Error(), Format(), Hex(), LCase(), Mid(), MidB(), Left(), LeftB(), 
LTrim(), Oct(), RightB(), Right(), RTrim(), Space(), Str(), String(),Trim(), UCase() 

Use these string version functions:

Chr$(), ChrB$(), ChrW$(), Error$(), Format$(), Hex$(), LCase$(), Mid$(), MidB$(), Left$(),
LeftB$(), LTrim$(), Oct$(), RightB$(), Right$(), RTrim$(), Space$(), Str$(), String$(),
Trim$(), UCase$()

25. Minimize data exchange between Worksheet and VBA code

Use an array to collect big range data and traverse through the array rather than a Worksheet range, cell by cell. This optimize VBA code tip allows to improve the performance more than 1o times.

Instead of this approach:

Function CalcSlow() As Double
    Dim cell As Range
    For Each cell In Sheet1.UsedRange
        If IsNumeric(cell.Value) Then
            CalcSlow = CalcSlow + cell.Value
        End If
    Next
End Function

Use this approach:

'the CalcFast() works more than x10 times faster of CalcSlow()
Function CalcFast() As Double
    Dim arrCells() As Variant
    Dim val As Variant
    arrCells = Sheet1.UsedRange.Value2
    For Each val In arrCells
        If IsNumeric(val) Then
            CalcFast = CalcFast + CDbl(val)
        End If
    Next
End Function
 

KL

Пользователь

Сообщений: 2186
Регистрация: 01.01.2013

e_artem, если позволите, в вашем разделе Оптимизация есть весьма сомнительные/спорные обобщения :)

1) избегать формул массива потому, что некоторые могут подвесить расчеты от непонимания того, как они действуют, — все равно, что избегать VBA потому, что можно по незнанию попасть в бесконечный цикл. Вопреки поверьям, формулы массива не медленнее, чем отдельные формулы их составляющие если сумма операций одна и та же. Формулы массива менее эффективны лишь тогда, когда алгоритм не оптимален: а. повторные расчеты, которых можно избежать, вынеся на лист как отдельные формулы, б. как частный случай, бинарные условные расчеты типа СУММПРОИЗВ(…), где нет возможности прекратить расчеты после нахождения искомого или где не был ограничен использованный диапазон. Точно также не все формулы массива длинные и непонятные :)

2) волатильность — не абсолютное зло, ее следует избегать в специфическом случае, когда сумма времен пересчета всех зависимых от нее формул достигает уровня создающего неудобства в работе с файлом, например 1 секунда и более (но последнее субъективно). Отказ от волатильных функций в других случаях может означать ненужные ограничения. Для примера, волатильны все функции времени и случайных чисел, а также СМЕЩ, ДВССЫЛ, ЯЧЕЙКА, ИНФОРМ и некоторые частные случаи неволатильных функций.

3) совсем непонятно избегание имен :) единственный недостаток я могу себе представить — это пересчет каждого упоминания имени в случае если зависимая формула пересчитывается, но это может быть проблемой лишь в случае «тяжелых» расчетов (например точного поиска или поиска по условиям) хранимых в имени. В этом смысле это то же, что и мой подпункт а. в пункте 1) этого списка.

6) злоупотреблять конечно не стоит, но на всякий случай, использование целых столбцов в функциях точного поиска и функции ИНДЕКС абсолютно не влияет на эффективность формулы. В случае функций неточного поиска, влияние нематериально даже при множестве повторов ввиду бинарного алгоритма. Реально известная проблема с этим — опять таки бинарные условные формулы типа СУММПРОИЗВ(…)

Изменено: KL20.01.2016 14:20:39

Понравилась статья? Поделить с друзьями:
  • Как ускорить запуск word
  • Как ускорить запись excel
  • Как ускорить вычисления в excel
  • Как ускорить выполнение макроса в excel
  • Как ускорить впр в excel