Skip to content

Working with Excel

Daniele Penza edited this page Dec 5, 2026 · 4 revisions

πŸ“Š Working with Excel

Evidence Scope

Every call into Excel crosses a boundary. The checker's workbook rules (PERF001, PERF002, PERF005-PERF008, PERF010, PERF012, PERF013, PERF021, PERF022) find the cell-by-cell patterns; this page adds the measured costs and the code for each fix. The rule list is on Skill Rules.

πŸ—‚οΈ On this page

πŸ”΄ DoEvents on every pass

πŸ“ 46 us per call: 1,700x a loop without it; about 4.6 s over 100,000 passes.

' ❌ yields to Windows 100,000 times
For i = 1 To n
    Total = Total + Values(i)
    DoEvents
Next i

' βœ… yields every 1,000 passes: cost close to zero, Excel stays responsive
For i = 1 To n
    Total = Total + Values(i)
    If i Mod 1000 = 0 Then DoEvents
Next i
Variant (20,000 passes) Median Ratio
No DoEvents 0.54 ms 1.0x
DoEvents every pass 917 ms 1,700x
If i Mod 1000 = 0 Then DoEvents 1.4 ms 2.6x
DoEvents every 0.1 s by a clock 1.5 ms 2.8x

Warning

A clock-based variant built on Timer breaks at midnight, when Timer returns to 0. Use a pass counter, or QueryPerformanceCounter.

πŸ”΄ Progress output and loop conditions

πŸ“ Run K, 5,000 passes of a small sum, with the VBA editor and the Immediate window open (two machines):

Variant Median Ratio
βœ… No output 0.21-0.52 ms 1x
βœ… If DEBUG_ON Then Debug.Print i with Const DEBUG_ON = False, or inside #If the same 1x
Debug.Print i every 1,000 passes 2.5-15 ms 12-40x
❌ Application.StatusBar = "Row " & i every pass 0.31-0.36 s 980-1,500x
❌ Debug.Print i every pass 2.2-8.9 s 10,700-24,000x
  • πŸ”΄ Debug.Print costs 0.45-1.8 ms per line with the editor open, of the order of deleting a row (0.86 ms). Keep debug output behind a Const or #Const flag: it then costs nothing. πŸ§ͺ The cost with the editor closed is still to be measured.
  • πŸ”΄ The status bar costs about 65 us per update, even with ScreenUpdating off: update it every 1,000 passes, like DoEvents.

πŸ“ Run K, the bound of a Do While loop read on every pass:

Condition Per pass Ratio to a local copy
βœ… last = ... before the loop, Do While i <= last 21-30 ns 1x
Do While i <= UBound(a) or Len(s) (1,000,000 passes) at most 4 ns more up to 1.14x
Do While i <= col.Count (Collection) 20-40 ns more 2x
Do While i <= d.Count (Dictionary, late bound) about 0.5 us 17-26x
❌ Do While i <= ws.Cells(ws.Rows.Count, 1).End(xlUp).Row 7 us 230-360x
❌ Do While i <= ws.UsedRange.Rows.Count 0.21 ms 7,200-10,600x
' ❌ asks Excel for the used range on every pass
Do While r <= ws.UsedRange.Rows.Count
    r = r + 1
Loop

' βœ… read the last row once
last = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
Do While r <= last
    r = r + 1
Loop

Warning

πŸ“ A bound copied before the loop does not see the loop change it: an array of 3 that grew to 6 inside the loop took 6 passes with UBound(a) in the condition, 3 with a local copy and 3 with For i = 1 To UBound(a), whose bound is read once. Hoist the bound only when the body cannot change it.

🟠 WorksheetFunction inside a loop

πŸ“ About 2.2 us per call, whatever the function: 25-32x the same logic in VBA.

' ❌ one call into Excel per row
m = Application.WorksheetFunction.Min(a, b, c)

' βœ… plain VBA
m = a
If b < m Then m = b
If c < m Then m = c
Task (per call) VBA WorksheetFunction Ratio
Minimum of three Double 69 ns 2,180 ns 32x
Round to 2 decimals 86 ns (Round) 2,164 ns 25x

βœ… One call over a whole array is fine: a single WorksheetFunction.Sort of 50,000 values ran at 1.14x a QuickSort written in VBA.

For rounding that matches Excel's ROUND, see Numbers and Dates.

🟠 Range.Value gives Variant arrays

πŸ“ Summing a Variant() costs 34 ns per element, 2x a Double() (17 ns); a Double() passed As Variant costs 2.8x.

Dim v As Variant, d() As Double, r As Long, c As Long
v = ws.Range("A2:T20001").Value2            ' one read: a 2-D Variant array

' βœ… worth copying to a typed array only when the data is read several times
ReDim d(1 To UBound(v, 1), 1 To UBound(v, 2))
For r = 1 To UBound(v, 1)
    For c = 1 To UBound(v, 2)
        d(r, c) = v(r, c)
    Next c
Next r

🟒 Loop order over a 2-D Variant block (rows or columns outer, or one For Each) made less than 12% difference.

⚠️ Excel state and errors

Public Sub RunHeavyWork()
    Dim su As Boolean, ev As Boolean, calc As XlCalculation
    su = Application.ScreenUpdating
    ev = Application.EnableEvents
    calc = Application.Calculation
    On Error GoTo Fail

    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Application.Calculation = xlCalculationManual

    ' ... read with one Range.Value, compute in arrays, write with one Range.Value ...

Finish:
    Application.Calculation = calc         ' restored on every path
    Application.EnableEvents = ev
    Application.ScreenUpdating = su
    Exit Sub
Fail:
    MsgBox "Error " & Err.Number & ": " & Err.Description
    Resume Finish
End Sub
Trap Why it matters
⚠️ End Stops at once and skips the handler: Calculation, ScreenUpdating and EnableEvents stay off
⚠️ A missing Set πŸ“ v = Range("A1") silently copies the default .Value (here Empty) instead of raising an error
⚠️ Debug.Assert False left in code VBA always runs inside its editor: it stops the user's macro

πŸ”΄ Reading and writing cells one at a time

πŸ“ Run I: read column A, write column C = A x 2.

Rows βœ… one .Value2 read, array loop, one write Cells read and write per row Cells read per row, one write
1,000 0.75 ms 31 ms (42x) 4.6 ms (6x)
10,000 6.9 ms 0.31 s (46x) 42 ms (6x)
100,000 72 ms 3.1 s (44x) 0.43 s (6x)

πŸ”΄ About 27 us per cell written and 3.6 us per cell read. The ratio does not grow with size: the cost is linear, but large.

πŸ“ Run H, writing 5,000 x 8 values:

Method Median Ratio
βœ… one Range.Value = 2-D array, ScreenUpdating off 51 ms 1.0x
one Range.Value, ScreenUpdating on 76 ms 1.5x
one Range.Value per row 0.23 s 4.4x
Cells(r, c).Value per cell 1.1 s 22x

Note

With a single Range.Value write, turning ScreenUpdating off saves a third; writing in one block saves far more. Text written to cells is converted with US rules: see Files and CSV.

🟒 .Value reads a block 5.1x slower than .Value2 (πŸ“ 36 ms against 6.9 ms for 200,000 cells): 0.14 us per cell, rarely worth changing. Choose by meaning: ⚠️ πŸ“ .Value returns a currency cell as Currency, rounded to 4 decimals (1.23456 β†’ 1.2346), and dates as Date.

πŸ”΄ Formatting cells one at a time

πŸ“ Run I, fill, bold and number format on 2,000 x 6 cells:

Method Median Ratio
βœ… one call on the block 3.7 ms 1.0x
one row at a time 0.43 s 117x
one cell at a time 2.2 s 595x

Formatting every other row (1,000 rows):

Method Median Ratio
βœ… one row at a time 0.19 s 1.0x
one row at a time, ScreenUpdating on 0.33 s 1.8x
❌ one Union of the rows, formatted once 0.39 s 2.1x

Warning

A Union of many separate areas costs more than it saves: building it grows with the number of areas. For data-dependent formats use conditional formatting or a style, or sort so the rows form a block.

πŸ”΄ Deleting rows in a loop

πŸ“ Run I, 2,500 scattered rows deleted out of 5,000:

Method Median Ratio
βœ… array: keep rows, clear, one write 14 ms 1.0x
Rows(r).Delete in a loop, bottom up 2.1 s 152x
AutoFilter, delete the visible rows 2.2 s 157x
❌ one Union of the rows, one Delete 7.6 s 538x

The code is on Skill Rules (PERF005).

Trap πŸ“ Evidence
⚠️ Deleting top-down in a For loop Skips the row after each delete: N N Y N N Y left N Y N Y
⚠️ SpecialCells with nothing to return Error 1004, for example after a filter that hides every row
⚠️ The array rebuild Fits only an isolated block of values: formulas become constants, row formatting stays where it was, columns outside the block keep their rows. Otherwise sort and delete one block

🟠 Select and the clipboard

πŸ“ Run I, writing 2,000 cells:

Method Median Ratio
βœ… ws.Cells(r, c).Value2 = r 58 ms 1.0x
.Select, then ActiveCell.Value2 = r 0.15 s 2.5x
the same, ScreenUpdating on 3.2 s 55x

πŸ“ Copying 10,000 x 5 values:

Method Median Ratio
src.Copy Destination:=dst 23 ms 1.0x
src.Copy, dst.PasteSpecial xlPasteValues 26 ms 1.15x
recorder: Select, Selection.Copy, Select, Paste 32 ms 1.4x
dst.Value2 = src.Value2 35 ms 1.55x (spread 25%)

🟒 The clipboard costs no time. Avoid it for its side effects: it replaces what the user copied, fails when another program holds it, and leaves Excel in copy mode until Application.CutCopyMode = False.

🟠 Whole columns

Task Range("A:A") Used block Ratio
πŸ“ Read 10,000 values, sum them in a loop to UBound 63 ms 1.5 ms πŸ”΄ 43x
πŸ“ 200 Match / CountIf 13 / 57 ms 13 / 56 ms 🟒 1.0x

A whole column costs time only when it is read into VBA (.Value2 returns 1,048,576 rows) and scanned; the read and the scan were timed together. Inside a worksheet function Excel stops at the used range.

πŸ”΄ Lookups against a table

πŸ“ Run J: a sorted two-column table, half of the keys missing.

Method 1,000 rows, 1,000 lookups 10,000 rows, 500 100,000 rows, 100
❌ keys.Find(k, LookAt:=xlWhole) 0.57 s 2.7 s 5.8 s
Application.VLookup(k, table, 2, False) 12 ms 26 ms 55 ms
Application.Match(k, keys, 0), then Cells(pos, 2) 15 ms 29 ms 54 ms
βœ… Application.Match(k, keys, 1) on sorted keys, check the key 14 ms 7.1 ms 1.6 ms
one read, Dictionary built, lookups in memory 3.2 ms 9.9 ms 136 ms
βœ… one read, binary search in the array 0.95 ms 1.4 ms 6.9 ms
  • πŸ”΄ Find is the slowest lookup by far: 46-106x VLookup, about 0.58 us per row of the table per lookup. Keep it for a single search.
  • 🟠 Exact VLookup and Match grow with the table: 12 us per lookup at 1,000 rows, 0.55 ms at 100,000.
  • 🟒 On sorted keys, Match(k, keys, 1) costs 15 us at any size: Excel searches by halves. Check that the key it found equals the one sought.
  • ⚠️ The Dictionary is not free: building it costs about 1.4 us per row, so it pays off above about 250 lookups. With 100 lookups in 100,000 rows it was 2.5x slower than VLookup.
' βœ… sorted keys: Excel's binary search, then check the match
Pos = Application.Match(Key, Keys, 1)
If Not IsError(Pos) Then
    If Keys.Cells(Pos, 1).Value2 = Key Then Result = Values.Cells(Pos, 1).Value2
End If

Warning

πŸ“ Approximate lookups assume keys sorted ascending: on keys 10 down to 1, VLookup(3, ..., True) returned #N/A. A missing key gives an error value through Application.VLookup and raises error 1004 through WorksheetFunction.VLookup.

πŸ”΄ Evaluate and [A1] in a loop

πŸ“ Run J, value x rate for 2,000 rows, the rate in B1:

Method Median Ratio
βœ… array, rate read once 0.23 ms 1.0x
βœ… one ws.Evaluate("A1:A2000*$B$1") 0.33 ms 1.4x
array, ws.Range("B1").Value2 per row 11 ms 48x
❌ array, [B1] per row 60 ms 259x
❌ ws.Evaluate("A" & r & "*$B$1") per row 66 ms 287x

Evaluate costs about 30 us per call, as much as writing a cell, and [B1] is an Evaluate: 5.4x reading the same cell through Range.

Warning

πŸ“ Application.Evaluate and [A1] read the active sheet: with another sheet active, [A1] returned 3 where ws.Evaluate("A1") returned 1. Use ws.Evaluate or a Range.

πŸ”΄ Calculation, volatile functions and the state guards

πŸ“ Run J, 300 writes feeding 2,000 simple formulas, calculation manual:

Method Median Ratio
βœ… one block write, one Application.Calculate 0.88 ms 1.0x
βœ… one Application.Calculate after the loop 11 ms 12x
Application.Calculate after each write 0.12 s 137x
Worksheet.Calculate after each write 0.13 s 148x
automatic calculation during the writes 0.12 s 132x
⚠️ Cells(r, 2).Calculate after each write 31 ms wrong: the SUM over the column kept its old value
❌ Application.Calculate per write, 500 volatile UDF cells on another sheet 1.6 s 1,850x

πŸ“ Run J, 100 writes to cells nothing depends on, beside 500 UDF cells, calculation automatic:

UDF cells Median Ratio
βœ… UDF not volatile 5.0 ms 1.0x
UDF volatile, calculation manual, one Calculate at the end 8.4 ms 1.7x
native volatile formula (RAND()) 41 ms 8x
❌ UDF with Application.Volatile 0.51 s 103x

πŸ“ Run J, 1,000 writes feeding formulas, with a change handler that only counts:

Guards Median Ratio
βœ… all three off, one block write 1.8 ms 1.0x
βœ… all three off, one Calculate at the end 35 ms 20x
Calculation manual only 0.16 s 89x
EnableEvents off only 0.50 s 282x
ScreenUpdating off only 0.52 s 296x
❌ no guard 0.62 s 350x
❌ no guard, 500 volatile UDF cells on another sheet 5.6 s 3,200x
  • πŸ”΄ Every write recalculates every volatile cell, wherever it is: about 10 us per volatile UDF cell, 5 ms per write for 500 cells.
  • πŸ”΄ Calculation is the guard that matters: manual alone 3.9x; then ScreenUpdating and EnableEvents off, 1.2x each with a handler that only counts (a real handler costs more). All three 17.5x; one block write 350x.
  • 🟒 Worksheet.Calculate costs the same as Application.Calculate when no sheet holds volatile cells.

Warning

πŸ“ Range.Calculate recalculates only its range: dependants outside it stay stale. Worksheet.Calculate skips volatile cells on other sheets (0 of 500 UDF calls). One block write fires one Change event whose Target holds every cell (1 event, 10 cells): a handler that reads Target.Value as one value breaks when a loop becomes a block write.

⚑ VBA Performance

Topics

Reference

Clone this wiki locally