VBA course · Lesson 30 of 33

Make your macros fast: speed optimization in VBA

Speed up slow macros: switch off screen updating, calculation and events safely, use arrays instead of cell-by-cell loops, avoid Select and measure with Timer.

Advanced 20 min read

A macro that takes four minutes is a macro nobody wants to run. The good news is that most slow VBA is slow for the same handful of reasons, and fixing them often turns minutes into seconds. This lesson explains why VBA code is slow, shows the settings that switch off Excel's busywork while a macro runs, and teaches the single most effective technique of all: working with arrays instead of individual cells.

Before you optimise anything, measure. Guessing where the time goes is unreliable; a stopwatch is not.

Measuring with Timer

Timer returns the number of seconds since midnight, with fractions. Read it before and after a block of code and print the difference in the Immediate window (Ctrl+G, Error handling and debugging in VBA).

VBA
Option Explicit

Sub MeasureSomething()
    Dim t As Double
    t = Timer

    ' ... the code you want to measure ...
    Dim i As Long, x As Double
    For i = 1 To 1000000
        x = x + Sqr(i)
    Next i

    Debug.Print "Took "; Format(Timer - t, "0.000"); " seconds"
End Sub
A simple stopwatch around any piece of code

Timer resets at midnight, so a measurement that crosses midnight comes out negative; for everyday tests that does not matter. Run a measurement two or three times: the first run is often slower because files and caches are still warming up.

Why VBA code is slow

VBA itself is fairly quick at arithmetic: the loop above adds a million square roots in a fraction of a second. What is slow is every trip between VBA and the worksheet. Each time your code reads or writes a cell, VBA has to call into Excel, Excel updates its internal data, possibly redraws the screen, possibly recalculates every dependent formula, and possibly fires a Worksheet_Change event. Do that 50,000 times and you wait.

So the two main strategies are:

  1. Tell Excel to stop doing extra work while the macro runs (screen drawing, recalculation, events).
  2. Talk to the worksheet less often: read a whole range into memory in one go, process it there, and write it back in one go.

Switching off Excel's busywork

SettingWhat it stopsRestore to
Application.ScreenUpdating = FalseRedrawing the screen after each changeTrue
Application.Calculation = xlCalculationManualRecalculating formulas after each changeThe previous mode (usually automatic)
Application.EnableEvents = FalseEvent macros firing (Worksheet_Change etc.)True
Application.DisplayAlerts = FalseConfirmation prompts (delete sheet, overwrite file)True
ActiveSheet.DisplayPageBreaks = FalseRecomputing page-break linesAs it was

ScreenUpdating usually gives the biggest win for macros that format or move many cells, Calculation for workbooks full of formulas, and EnableEvents when the sheet you write to has a change event (Events: macros that run by themselves).

The danger is forgetting to switch them back. A workbook left in manual calculation shows stale totals, and with events off, your carefully written timestamp macro silently stops working until Excel restarts. The settings belong to the application, not the workbook, so they also affect every other open file.

A reusable, error-safe speed switch

Wrap the settings in two procedures and always restore them in an exit section that runs even after an error.

VBA
Option Explicit

Private mCalcMode As XlCalculation
Private mIsFast As Boolean

Public Sub SpeedOn(Optional ByVal statusText As String = "Working...")
    If mIsFast Then Exit Sub               ' already on: do not overwrite saved mode
    mCalcMode = Application.Calculation    ' remember the user's mode
    With Application
        .ScreenUpdating = False
        .EnableEvents = False
        .Calculation = xlCalculationManual
        .StatusBar = statusText
    End With
    mIsFast = True
End Sub

Public Sub SpeedOff()
    If Not mIsFast Then Exit Sub
    With Application
        .Calculation = mCalcMode
        .EnableEvents = True
        .ScreenUpdating = True
        .StatusBar = False                 ' give the status bar back to Excel
    End With
    mIsFast = False
End Sub
Module modSpeed: switch speed mode on and off safely
VBA
Option Explicit

Sub RebuildReport()
    On Error GoTo CleanUp
    SpeedOn "Rebuilding the sales report..."

    ' ... the real work: copy, format, fill formulas ...
    ThisWorkbook.Worksheets("Report").Range("A2:H5000").ClearContents

CleanUp:
    SpeedOff                                ' runs after success AND after an error
    If Err.Number <> 0 Then
        MsgBox "Report stopped: " & Err.Description, vbExclamation
    End If
End Sub
Using the speed switch with an error handler

The label CleanUp sits before the final lines, so execution reaches it both when the work finishes normally and when an error jumps there. This pattern is worth memorising; the final project (Final project: build a PDF invoice generator in VBA) uses it too.

Tip. Use the status bar to show progress in long loops, for example Application.StatusBar = "Processing file " & i & " of " & n. It costs almost nothing and reassures users that Excel has not frozen. Add DoEvents every few hundred iterations if you want the window to stay responsive.

Arrays instead of cell-by-cell loops

This is the big one. Compare two ways of adding 20% VAT to 50,000 net amounts in column B and writing the result to column C.

VBA
Option Explicit

Sub AddVatSlow()
    Dim ws As Worksheet
    Dim r As Long
    Dim t As Double
    t = Timer
    Set ws = ThisWorkbook.Worksheets("Data")
    For r = 2 To 50001
        ws.Cells(r, "C").Value = ws.Cells(r, "B").Value * 1.2
    Next r
    Debug.Print "Slow: "; Format(Timer - t, "0.00"); " s"
End Sub
Slow: one read and one write per cell
VBA
Option Explicit

Sub AddVatFast()
    Dim ws As Worksheet
    Dim net As Variant
    Dim gross() As Variant
    Dim r As Long
    Dim t As Double
    t = Timer
    Set ws = ThisWorkbook.Worksheets("Data")

    net = ws.Range("B2:B50001").Value2          ' 2-D array (1 To 50000, 1 To 1)
    ReDim gross(1 To UBound(net, 1), 1 To 1)

    For r = 1 To UBound(net, 1)
        If IsNumeric(net(r, 1)) Then
            gross(r, 1) = net(r, 1) * 1.2
        End If
    Next r

    ws.Range("C2").Resize(UBound(gross, 1), 1).Value2 = gross
    Debug.Print "Fast: "; Format(Timer - t, "0.00"); " s"
End Sub
Fast: one read, work in memory, one write

On a typical laptop the slow version takes several seconds (much more if the sheet has formulas or events), the fast version a few hundredths of a second. The loop is the same; only the number of trips to the worksheet changed from 100,000 to 2. Arrays are covered in depth in Arrays in VBA: static, dynamic and fast range processing. Remember that Range.Value always gives a 2-D array starting at 1, even for a single column.

Value2

.Value2 reads the raw cell content without converting currency and dates into VBA's Currency and Date types. It is slightly faster and avoids rounding surprises with currency-formatted cells; the downside is that dates come back as serial numbers (46023 for 1 January 2026). Use .Value when you need real dates in VBA, .Value2 for plain numbers and text.

Stop selecting things

The macro recorder (The macro recorder: record, read and clean up code) writes code like this:

VBA
Sub FormatHeaderRecorded()
    Sheets("Report").Select
    Range("A1:F1").Select
    Selection.Font.Bold = True
    Selection.Interior.Color = RGB(221, 235, 247)
    Range("A1").Select
End Sub
Recorded style: selects everything

Every Select forces Excel to switch sheets, move the cursor and redraw. It also makes code fragile: if the user clicks elsewhere while it runs, Selection is something else. Refer to objects directly instead, and use With to avoid repeating the same reference:

VBA
Option Explicit

Sub FormatHeader()
    With ThisWorkbook.Worksheets("Report").Range("A1:F1")
        .Font.Bold = True
        .Interior.Color = RGB(221, 235, 247)
        .HorizontalAlignment = xlCenter
        .EntireColumn.AutoFit
    End With
End Sub
Direct references with a With block

With evaluates ThisWorkbook.Worksheets("Report").Range("A1:F1") once and reuses it for every line starting with a dot. Besides speed, it makes the code easier to read.

Doing things in bulk

Many actions are much faster on a whole range at once than on single cells:

  • Formats: format Range("C2:C50001") in one statement, not in a loop.
  • Formulas: write one formula to a whole column with Range("D2:D50001").Formula = "=B2*C2"; Excel adjusts the relative references for each row.
  • Deleting rows: deleting rows one by one is slow, and deleting inside a top-down loop skips rows. Collect them with Union and delete once, or use AutoFilter (Find, filter and sort data with VBA).
VBA
Option Explicit

Sub DeleteCancelledRows()
    Dim ws As Worksheet
    Dim lastRow As Long
    Dim r As Long
    Dim toDelete As Range

    Set ws = ThisWorkbook.Worksheets("Orders")
    lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

    For r = 2 To lastRow
        If ws.Cells(r, "E").Value = "Cancelled" Then
            If toDelete Is Nothing Then
                Set toDelete = ws.Rows(r)
            Else
                Set toDelete = Union(toDelete, ws.Rows(r))
            End If
        End If
    Next r

    If Not toDelete Is Nothing Then toDelete.Delete
End Sub
Delete all rows with status "Cancelled" in one go
ABCDE
1OrderCustomerDateAmountStatus
2SO-501Acme Ltd2026-03-021200Shipped
3SO-502Brightway2026-03-02450Cancelled
4SO-503Coastline Foods2026-03-03980Open
5SO-504Acme Ltd2026-03-04300Cancelled

Before: column E holds the status; rows 3 and 5 will be deleted in one operation

For very many scattered rows (tens of thousands), Union itself becomes slow. Then the fastest approach is to sort the data so the unwanted rows sit together, or to filter the data into an array and write back only the rows you keep.

Myths and smaller tips

  • "Integer is faster than Long." Not on modern computers. VBA converts Integer to Long internally, and Integer overflows above 32,767, a classic bug with row numbers. Use Long for whole numbers (Variables and data types: Dim, Option Explicit and scope).
  • "Variant is always slow." Variants are a little slower than typed variables, but reading a range into a Variant array is the fastest thing you can do. Type individual variables, and use Variant where Excel requires it.
  • Avoid Copy and Paste when you only need values: target.Value = source.Value skips the clipboard entirely.
  • Use the Find method or MATCH via Application.Match instead of looping through 100,000 cells to look for one value (Using Excel worksheet functions in VBA).
  • Volatile formulas such as INDIRECT, OFFSET and NOW in a big workbook slow down every recalculation, macro or not.
  • Do not optimise what is already fast. A macro that runs once a month in two seconds does not need arrays. Readability counts too.

Mac notes

All the settings in this lesson work on Excel for Mac. Screen redrawing is relatively more expensive on the Mac, so ScreenUpdating = False often makes an even bigger difference there. DoEvents also works, but calling it in every loop iteration slows things down noticeably; call it every few hundred rows.

Common mistakes

  • Turning settings off without an error handler, so a crash leaves Excel in manual calculation with events disabled.
  • Restoring calculation to xlCalculationAutomatic unconditionally, even when the user had chosen manual on purpose. Save and restore the previous mode instead.
  • Forgetting that a sheet with formulas still needs a calculation before you read results while calculation is manual: call ws.Calculate or Application.Calculate first.
  • Writing an array back to a range of a different size, which either cuts data off or fills extra cells with #N/A.

Check yourself

1. What makes most slow VBA code slow?

2. Why should SpeedOff run in a label that is reached after an error as well?

3. What does Range("B2:B10").Value return?

4. What is the best way to delete 300 scattered rows that match a condition?

5. Which statement about Integer and Long is true?