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

Хитрости »

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


Рано или поздно у пишущих на 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
ссылки
статистика

Время на прочтение
4 мин

Количество просмотров 127K

image

Предисловие

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

Перед началом работы

Перед тем, как перейти прямо к сути, я хотел бы обратить внимание на пост: Несколько советов по работе с VBA в Excel. В частности, в блоке “Ускорение работы макросов” есть полезные примеры кода, которые стоит использовать вместе с моими советами по ускорению работы, для достижения максимального результата.

Ускоряем работу макроса

Итак, к сути… Для того что бы реально ускорить работу VBA в Ecxel нужно понимать, что обращение к ячейке на листе — занимает значительно время. Если Вы хотите записать в ячейку одно значение, то это не займет значительного времени, но если Вам потребуется записать(прочитать, обратиться) к тысячам ячеек, то это потребует гораздо большего времени. Что же делать в таких случаях? На помощь приходят массивы. Массивы хранятся в памяти, а операции в памяти VBA выполняет в сотни, а то и в тысячи раз быстрее. Поэтому, если у Вас в данных тысячи, сотни тысяч значений, то время выполнения макроса может занимать от нескольких минут до нескольких часов, а если эти данные перенести в массив, то выполнение макроса может сократиться до нескольких секунд (минут).

Я наведу пример кода и в комментариях объясню что к чему, так будет яснее. К тому же, могут пригодиться некоторые строки кода, не относящееся прямо к процессу ускорения.

Пример

Предположим, что у нас есть данные на “Лист1” (“Sheet1”). Данные содержаться в 50 колонках (колонки содержат названия) и 10 000 строк. К примеру, нам нужно в последнюю колонку внести значение, которое равно значению во второй колонке, деленное на значение в третьей колонке (начиная со 2-й строки, так как первая содержит заглавие). Потом мы возьмем первые 10 колонок и скопируем их на “Лист2” (“Sheet2”), для дальнейшей обработки (для других потребностей). Пусть пример и банальный, но, как мне кажется, он может отобразить всю суть данного поста.

'Для явной инициализации переменных, включаем эту опцию
'Это поможет избежать многих ошибок
Option Explicit

Sub Test()

'К листам будем обращаться через переменные
Dim Sheet1_WS, Sheet2_WS As Worksheet
'Переменная для прохождения срок на листе (в массиве)
Dim i As Long

'Массив, в котором будут храниться наши данные
Dim R_data As Variant
'Переменные последней строки и колонки
Dim FinalRow, FinalColumn As Long

'Можно инициализировать лист не по названию, а по порядковому номеру
'Set Sheet1_WS = Application.ThisWorkbook.Worksheet("Sheet1")
Set Sheet1_WS = Application.ThisWorkbook.Sheets(1)
Set Sheet2_WS = Application.ThisWorkbook.Sheets(2)

'Поиск последней не пустой строки в первой колонке
'Нужно, что бы данные не были отфильтрованы, иначе последняя строка будет последней строкой в фильтре
'Также в последней строке, в первой колонке, не должно быть пустой ячейки. Конечно, если в этой строке вообще есть данные. Иначе последней строкой будет последняя не пустая ячейка.
FinalRow = Sheet1_WS.Cells(Rows.Count, 1).End(xlUp).Row '=10 000

'Поиск последней не пустой колонки в первой строке
FinalColumn = Sheet1_WS.Cells(1, Columns.Count).End(xlToLeft).Column '=50

'Присваиваем массиву диапазон данных на Листе 1
R_data = Sheet1_WS.Range(Sheet1_WS.Cells(1, 1), Sheet1_WS.Cells(FinalRow, FinalColumn))

For i = 2 To FinalRow
    'Выполняем нужные нам операции с данными.
    'Проверяем, что бы не было деления на ноль.
    'Предполагается, что в колонке 2 и 3 стоят числовые данные
    'Иначе потребуется обработка ошибок
    If R_data(i, 3) <> 0 Then
        R_data(i, FinalColumn) = R_data(i, 2) / R_data(i, 3)
    End If
Next i

'Копируем данные из массива обратно на Лист1
'Перед этим очищаем данные на листе (если есть форматирование или формулы, то лучше Sheet1_WS.Cells.ClearContents)
Sheet1_WS.Cells.Delete
Sheet1_WS.Range(Sheet1_WS.Cells(1, 1), Sheet1_WS.Cells(FinalRow, FinalColumn)) = R_data

'Копируем данные на Лист2, копируем первые 10 колонок.
Sheet2_WS.Range(Sheet2_WS.Cells(1, 1), Sheet2_WS.Cells(FinalRow, 10)) = R_data

'Закрываем книгу и сохраняем её
Workbooks(Application.ThisWorkbook.Name).Close SaveChanges:=True

End Sub

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

Dim R_new() As Variant
............................................
' Явно указываем размер массива

ReDim R_new(1 To FinalRow, 1 To 50) As Variant
...........................................
Sheet1_WS.Range(Sheet1_WS.Cells(1, 1), Sheet1_WS.Cells(FinalRow, 50)) = R_new()

Заключение

Большинство операций над данными можно выполнять в массиве, при этом, отображать на лист только результат. Иногда целесообразным бывает показать результат на лист, потом выполнить некоторые действия (например, сортировку) и снова загрузить данные в массив.

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

В дальнейшем я планирую написать советы (примеры) по быстрому поиску данных на листе, но это уже будет другой пост. Если будут вопросы, комментарии, пожалуйста, пишите.

Спасибо за внимание. Удачных разработок.

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.

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

Если вы хотите, чтобы ваш код макроса 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 ) Удалить избыточное форматирование

 

KL

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

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

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

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

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

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

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

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

Skip to content

Optimize VBA Code to run Macros Faster

Home » VBA » Optimize VBA Code to run Macros Faster

  • Excel VBAOptimize VBA Code to run Macros Faster

Please find the following information to optimize VBA code to run macros faster, simple, easy to understand and efficient way of writing macro. It will save lot of time while running macros and best of writing or practice for effective VBA codes or macros in Excel. The following tips or tricks are the best choice for excellent VBA programmers to write codes in an efficient manner.

Why we need to Optimize VBA Code?

We need to Optimize VBA codes to run macros Faster while running VBA macro for efficient VBA programming, to generate good quality of output, to save time, easy to understand codes, etc.

Excel VBAOptimize VBA Code to run Macros Faster

VBA Optimize Technics to Run Macros Faster

We can fasten the execution of macros or VBA Procedures or functions by following or using the below tips or technics.

  • Turn off ScreenUpdating
  • Turn off Automatic Calculations
  • Disable Events
  • Avoid Using Variant DataType
  • Use ‘WITH’ Statement
  • Avoid Recording Macro
  • Use ‘vbNullString’ instead of “”
  • Reduce the number of lines using Colon(:)
  • Use best approach to Copy and Paste

1.Turn off Screen Updating

It will help you to stop screen flickering or Screen updating while executing or running macro. So that it will greatly speed up your code and saves lot of time. Please find the following statements for better understand.

Sub Stop_ScreenUpdation ()
    Application.ScreenUpdating = False
    '...Statemets (Your Code)
    Application.ScreenUpdating = True
End Sub

Explanation: Use Application.ScreenUpdating = False at the beginning of your code and Application.ScreenUpdating = True before ending of your code.

2.Turn off ‘Automatic Calculations’

It will help you to prevent calculations while executing or running macro. So that it will greatly speed up your code and saves lot of time. If you don’t mention this may cause too often calculation in workbook. So that performance will come down. Please find the following statements for better understand.

Sub Stop_Calculation()
    Application.Calculation = xlCalculationManual
    '...Statemets(Your Code)
    Application.Calculation = xlCalculationAutomatic
End Sub 

Explanation: Use Application. Calculation = xlCalculationManual at the beginning of your code and Application. Calculation = xlCalculationAutomatic before ending of your code.
Note: Other way of stopping calculation in workbook is change calculation mode is xlCalculationManual. So that Excel does not calculate values in the workbook cells.

3.Disable Events

It will help you to prevent or stop endless loops while executing or running macro if you have worksheet or workbook events. So that it will greatly speed up your code and saves lot of time. Please find the following statements for better understand.

Sub Stop_Events()
    Application.EnableEvents = False
    '...Statemets
    Application.EnableEvents = True
End Sub

Explanation: Use Application. EnableEvents = False at the beginning of your code and Application. EnableEvents = True before ending of your code.

5.Use ‘WITH’ Statement

Use ‘WITH’ statement when working with Objects in macro. If you are using several statements with same object, use a ‘WITH’ statement rather than using all the used statements. Please find the following statements for better understand.

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

‘Instead of using below macro use above macro for faster process.

Sub Without_WITH()
     Worksheets("Sheet1").Range("A1").Value = 100
    Worksheets("Sheet1").Range("A1").Font.Bold = True
End Sub

Explanation: In the above procedure we have used ‘With’ statement to optimize the macro.

6.Avoid Recording Macro

Always better avoid recording macro. It will show effect on his performance. Please find the below example for better understand on avoid recording macro.
Example: Change cell (“D6”) color to yellow and font is bold.
If you record macro, the code is looking like below.
Recorder Macro:

Sub Macro1()
'
' Macro1 Macro
'
'
    Range("D6").Select
    Selection.Font.Bold = True
    With Selection.Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .Color = 65535
        .TintAndShade = 0
        .PatternTintAndShade = 0
    End With
End Sub

The recorded macro can also be written like below.
Written Macro:
Please find the below macro, it will change the cell (“C5”) color and font as bold.

Sub Change_Cell_Font()
    With Range("C5")
        .Font.Bold = True
        .Interior.Color = 65535
    End With
End Sub

If you compare recorded macro and written macro so much of difference will be there. I think already you stood by seeing above examples.

7.Use vbNullString instead of “”

The ‘vbNullString is a Constant. It denotes a null String. It occupies less memory compares to “” and faster in process and to assign. And “” represents empty string and occupies more memory compares to vbNullString. So always better to use vbNullString instead of “”.

8.Reduce the number of lines using colon (:)

Few statements we can write in a single line instead of multiple lines. Please find the below examples for better understand.

Example1: We can declare the variables in the following way.

Sub Declare_Variables()
    Dim iCnt As Integer, jCnt As Integer    
End Sub

‘Instead of using below macro use above macro for faster process.

Sub Declare_Variables1()
     Dim iCnt As Integer
    Dim jCnt As Integer    
End Sub

The first macro will process faster compares to second procedure.

Example2: Use colon (:) to write multiple statements in a single line in the following way.

Sub Use_Colon_ForMultipleLine()
    Dim iCnt As Integer, jCnt As Integer
    iCnt = 5: jCnt = 10
End Sub

‘Instead of using below macro use above macro for faster process.

Sub Use_Colon_ForMultipleLine1()
    Dim iCnt As Integer, jCnt As Integer
    iCnt = 5
    jCnt = 10
End Sub

The first macro will process faster compares to second procedure.

9.Use best approach to Copy and Paste

Please find the below different examples for better understand to use best approach to Copy and Paste.
Example:

Sub CopyPaste_Ex2()
    Sheets("Source").Range("A1:E10").Copy Destination:=Sheets("Destination").Range("A1")
End Sub

‘Instead of using below macro use above macro for faster process.

Sub CopyPaste_Ex1()
    Sheets("Source").Range("A1:E10").Copy
    Sheets("Destination").Range("A1").PasteSpecial
    Application.CutCopyMode = False
End Sub
Effortlessly Manage Your Projects and Resources
120+ Professional Project Management Templates!

A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.

Save Up to 85% LIMITED TIME OFFER
Excel VBA Project Management Templates
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates

Excel Pack
50+ Excel PM Templates

PowerPoint Pack
50+ Excel PM Templates

MS Word Pack
25+ Word PM Templates

Ultimate Project Management Template

Ultimate Resource Management Template

Project Portfolio Management Templates

Related Posts

VBA Reference

Effortlessly
Manage Your Projects

120+ Project Management Templates

Seamlessly manage your projects with our powerful & multi-purpose templates for project management.

120+ PM Templates Includes:

11 Comments

  1. tomas
    April 29, 2015 at 2:11 PM — Reply

    in first code snipet there is twice screen updating = false

  2. PNRao
    April 29, 2015 at 9:37 PM — Reply

    I have rectified the code. It’s a typo error. Thanks for notifying me.

    Regards,
    Valli

  3. Venkat
    August 31, 2015 at 5:02 PM — Reply

    Hi Mr.P.N.Rao ! In your blog section “OPTIMIZE TOUR VBA CODE ” the following is the text .It seems the code written is contradicting..Kindly let me know if I am wrong ….

    3.Disable Events

    It will help you to prevent or stop endless loops while executing or running macro if you have worksheet or workbook events. So that it will greatly speed up your code and saves lot of time. Please find the following statements for better understand.

    Sub Stop_Events()
    Application.EnableEvents = False
    ‘…Statemets
    Application.EnableEvents = False
    End Sub

    Explanation: Use Application. EnableEvents = False at the beginning of your code and Application. EnableEvents = True before ending of your code.

  4. Charollete
    February 15, 2016 at 6:00 PM — Reply

    I have followed your script, and utilized it in my code to move files(converted files) from source to destination folder. I have few extensions which cannot be moved from source tod estination, since the error is file not found.

    I have traced the issue that the file which is getting converted and placed in source is more than one file. To be simple the source file is pdf, let say it contains 7 pages and it converts into jpeg image and that will be 7 jpeg files ofthe source. When my amcro executes, it looks for the filename of the source the destination file and concatenates with the destination pathto move the file. since the file name contains a suffix as Filename_Page_1 to Filename_Page_7, this error occurs and couldnt process for few extensions like this.

    If the file extension is word or excel of my source file(pdf- 7 pages) the output is always 1 page. However the issue occurs only when the file extensions or other than this (jpx, jpf, j2k, jpc).

  5. Naveen prajapati
    March 3, 2017 at 9:30 PM — Reply

    Thank you so much 2 no. Automatic Calculation is good for me

  6. Nick
    April 12, 2017 at 2:20 PM — Reply

    I’m an Excel developer with 12 years experience, and thought I’d let you know that I never knew that the colon (:) to reduce lines in the VBA script could speed up the VBA process. Great tip !

  7. PNRao
    April 12, 2017 at 2:26 PM — Reply
  8. Sabhajeet kumar
    November 4, 2017 at 3:15 AM — Reply

    Great explain sir.
    Heartly thanks

  9. Paul
    August 8, 2019 at 8:27 AM — Reply

    Disable Events
    This should be done within a code block being careful to note when an event should be triggered for proper function and when it should not e.g. should you change the active worksheet and there is a macro attached to the activate event of that worksheet, it will not be triggered if events are disabled.

  10. Jaka Strojansek
    September 28, 2020 at 3:10 PM — Reply

    Hello! I have written an app in excel environment that includes multiple macros. After a few runs the app is noticeably slower. Can I send you vba so you can double check if there is any room for improvement? Thank you for your help. Greetings from Slovenia, Jaka.

  11. Hak Sokly
    November 29, 2020 at 6:56 AM — Reply

    I could not run the code of Copy and Paste Approach. Could you explain me about the sheets(“destination”) and sheets(“source”)? What do they mean to you?

Effectively Manage Your
Projects and  Resources

With Our Professional and Premium Project Management Templates!

ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.

We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.

Project Management
Excel VBA

Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.

Analysistabs Logo

Page load link

VBA Projects With Source Code

3 Realtime VBA Projects
with Source Code!

Take Your Projects To The Next Level By Exploring Our Professional Projects

Go to Top

Понравилась статья? Поделить с друзьями:
  • Как ускорить работу word
  • Как ускорить работу excel с большими таблицами
  • Как ускорить открытие большого файла excel
  • Как ускорить макрос vba excel
  • Как ускорить запуск word