Repository navigation
Working with Excel
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.
- π΄
DoEventson every pass - π΄ Progress output and loop conditions
- π
WorksheetFunctioninside a loop - π
Range.ValuegivesVariantarrays β οΈ Excel state and errors- π΄ Reading and writing cells one at a time
- π΄ Formatting cells one at a time
- π΄ Deleting rows in a loop
- π
Selectand the clipboard - π Whole columns
- π΄ Lookups against a table
- π΄
Evaluateand[A1]in a loop - π΄ Calculation, volatile functions and the state guards
π 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.
π 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.Printcosts 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 aConstor#Constflag: 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
ScreenUpdatingoff: update it every 1,000 passes, likeDoEvents.
π 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
LoopWarning
π 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.
π 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.
π 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.
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 |
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 |
π 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.
π 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.
π 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 |
|---|---|
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 |
| 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 |
π 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.
| 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.
π 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 |
- π΄
Findis the slowest lookup by far: 46-106xVLookup, about 0.58 us per row of the table per lookup. Keep it for a single search. - π Exact
VLookupandMatchgrow 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. β οΈ TheDictionaryis 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 thanVLookup.
' β
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 IfWarning
π 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.
π 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.
π 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
ScreenUpdatingandEnableEventsoff, 1.2x each with a handler that only counts (a real handler costs more). All three 17.5x; one block write 350x. - π’
Worksheet.Calculatecosts the same asApplication.Calculatewhen 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.
π Figures: Excel 365 (16.0 build 20723) 64-bit, Windows desktop, median of 5 runs Β· Raw data in docs/benchmarks/
- π Home
- π Measurement Method
Topics
- π Working with Excel
- π¦ Passing Data
- π€ Strings
- π’ Numbers and Dates
- π Searching, Sorting and Collections
- π§© Calls, Classes and Binding
- π Files and CSV
- πͺ Windows API on 64-bit Office
Reference
β οΈ Correctness Traps- π§° Skill Rules