Skip to content

Skill Rules

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

๐Ÿงฐ Skill Rules

Rules Measured To measure Correctness

These pages match release v1.0.0: 25 rules, severities as in the checker's --list-rules. The vba-performance skill finds slow patterns with a static checker (check_vba_perf.py) and fixes them with the patterns in references/patterns.md. This page lists every rule with its measurement status: ๐Ÿ“ timed on Excel 365 64-bit (see the linked page), or ๐Ÿงช recommended from experience and still to be measured. ๐Ÿงช figures are the skill's estimates, not measurements.

๐Ÿ—‚๏ธ On this page

๐Ÿ“‹ All rules at a glance

๐Ÿ“Š Workbook interaction

Rule Severity Pattern Status
PERF001 MEDIUM (HIGH in a loop); Selection / ActiveCell reads LOW (MEDIUM in a loop) .Select / .Activate; Selection / ActiveCell reads ๐Ÿ“ 2.5x; 55x with ScreenUpdating on (Working with Excel)
PERF002 HIGH Range / Cells / .Value / .Font ... inside a loop ๐Ÿ“ 31 us per row, 42-46x at any size; formatting per cell 595x (Working with Excel)
PERF005 HIGH Rows or cells deleted or inserted inside a loop ๐Ÿ“ 0.86 ms per delete, 152x an array rebuild; Union no fix (Working with Excel)
PERF006 MEDIUM (HIGH in a loop) .Copy / .Paste / .PasteSpecial (clipboard) ๐Ÿ“ no speed cost (1.0-1.55x); side effects only (Working with Excel)
PERF007 HIGH VLookup / Match / CountIf / .Find inside a loop ๐Ÿ“ VLookup 12 us to 0.55 ms per lookup with table size; Find 46-106x VLookup (Working with Excel)
PERF008 MEDIUM Evaluate / [A1] inside a loop ๐Ÿ“ 30 us per call, 260-290x VBA (Working with Excel)
PERF010 HIGH Calculate inside a loop ๐Ÿ“ 11x once after the loop; 137x one block write (Working with Excel)
PERF012 MEDIUM Whole column or row (Range("A:A"), .EntireColumn.Value) ๐Ÿ“ 43x to read and scan in VBA; none inside Match / CountIf (Working with Excel)
PERF013 MEDIUM Application.Volatile ๐Ÿ“ every write recalculates every cell: 10 us each, 103x non-volatile (Working with Excel)
PERF021 MEDIUM Sheet writes in a loop with no ScreenUpdating = False ๐Ÿ“ with formulas: calculation manual 3.9x, screen and events 1.2x each, all three 17.5x; 1.8x formatting per row, 22x Select per cell (Working with Excel)
PERF022 MEDIUM ScreenUpdating / Calculation / EnableEvents turned off and never restored โš ๏ธ correctness (Working with Excel)

๐Ÿงฎ Pure VBA

Rule Severity Pattern Status
PERF003 HIGH S = S & X inside a loop ๐Ÿ“ 11-35x (Strings)
PERF004 HIGH ReDim Preserve inside a loop ๐Ÿ“ 0.08-0.42 us per item, 2.4-6.7x sizing once; a Collection is slower still (Searching, Sorting and Collections)
PERF009 MEDIUM DoEvents on every iteration ๐Ÿ“ 1,700x (Working with Excel)
PERF011 LOW CreateObject / New inside a loop ๐Ÿ“ Scripting.Dictionary 0.4 ms per creation, FileSystemObject 7-10 us more than one reused (Calls, Classes and Binding), RegExp 3.6 us (Strings), New Collection 0.25 us
PERF014 LOW Implicit Variant (Dim A, B As Long) ๐Ÿ“ not slower in a simple loop; test to repeat (Numbers and Dates)
PERF015 LOW As Integer ๐Ÿ“ no practical gain (Integer 10% faster in a simple loop); overflows at 32,767 (Numbers and Dates)
PERF016 LOW Left / Mid / Trim ... without $ in a loop ๐Ÿ“ 1.16x (Strings)
PERF017 LOW Dim X As New T ๐Ÿ“ no speed cost; correctness trap (Calls, Classes and Binding)
PERF018 LOW IIf in a loop ๐Ÿ“ 3.2-3.7x If, about 0.1 us per call; Switch 5.5x (Calls, Classes and Binding)
PERF019 MEDIUM Col(i) on a Collection inside For i = 1 To Col.Count ๐Ÿ“ 520x (Searching, Sorting and Collections)
PERF020 LOW Debug.Print in a loop ๐Ÿ“ 0.45-1.8 ms per line with the editor open, 10,700-24,000x; nothing behind a False constant or #If (Working with Excel)
PERF023 INFO Three or more nested loops ๐Ÿ“ quadratic growth (Searching, Sorting and Collections)
PERF024 LOW Do While / While condition with .Count / UBound / Len ๐Ÿ“ UBound / Len a few ns, Collection.Count 2x; End(xlUp) 7 us and UsedRange 0.2 ms per pass (Working with Excel)
PERF025 LOW (HIGH when the procedure walks the array or indexes it in 2-D and is called inside a loop in the same file) ByVal ... As Variant (or untyped ByVal) indexed as an array ๐Ÿ“ 3.4 ms per call for 10,000 x 20, 26,000x ByRef (Passing Data)

Note

Severities are the defaults. A finding of a rule that reports a statement inside a loop drops one level (HIGH to MEDIUM, MEDIUM to LOW, LOW to INFO) when every open loop is small and fixed: For with numeric literal bounds and at most 10 passes, or For Each over an Array(...) of at most 10 items. A small loop inside a large one keeps its level.

Tip

Save the first run with --json > before.json and re-run after the fix with --baseline before.json: only the findings that are new or more severe than before are listed, matched within each file by rule, procedure and code (line numbers do not matter), with counts of the fixed and unchanged ones. --fail-on counts only the listed findings.

๐Ÿ”ฌ Rules in detail

Each section gives the slow form and the fix the skill proposes, then the measured figures (๐Ÿ“) or what is still to be measured (๐Ÿงช).

๐Ÿ“ PERF002 โ€” reading, writing and formatting cells one at a time

The skill's most common finding. Every Range, Cells or .Value call crosses into Excel.

' โŒ two calls into Excel per row
For RowIndex = 2 To LastRow
    Ws.Cells(RowIndex, 3).Value = Ws.Cells(RowIndex, 1).Value * 2
Next RowIndex

' โœ… one read, one write
Dim Data As Variant
Data = Ws.Range(Ws.Cells(2, 1), Ws.Cells(LastRow, 3)).Value2
For RowIndex = 1 To UBound(Data, 1)
    Data(RowIndex, 3) = Data(RowIndex, 1) * 2
Next RowIndex
Ws.Range(Ws.Cells(2, 1), Ws.Cells(LastRow, 3)).Value2 = Data
Skill estimate 10x-1,000x on thousands of rows
๐Ÿ“ Run I Read and write per row: 31 us per row (about 27 us per write, 3.6 us per read); 42x / 46x / 44x one block at 1,000 / 10,000 / 100,000 rows: the ratio stays, the cost is linear
๐Ÿ“ Run I Formatting 2,000 x 6 cells: per row 117x, per cell 595x one call on the block
๐Ÿ“ Run H Writing 5,000 x 8 values: per cell 1.1 s, per row 0.23 s, one Range.Value 51 ms (22x and 4.4x)

Warning

๐Ÿ“ A one-cell range returns a scalar, not an array. Writing the array back turns formulas in the block into values. .Value2 returns dates and currency as Double; .Value rounds currency cells to 4 decimals (1.23456 โ†’ 1.2346).

๐Ÿ“ PERF001 / PERF006 โ€” Select, Activate and the clipboard

' โŒ recorder style
Sheets("Data").Select
Range("A1:D100").Select
Selection.Copy
Sheets("Out").Select
Range("A1").PasteSpecial xlPasteValues

' โœ… references, no clipboard
With ThisWorkbook.Worksheets("Data").Range("A1:D100")
    ThisWorkbook.Worksheets("Out").Range("A1").Resize(.Rows.Count, .Columns.Count).Value2 = .Value2
End With
๐Ÿ“ Select (run I) .Select + ActiveCell per cell: 2.5x a direct write with ScreenUpdating off (44 us per Select); 55x with it on (1.6 ms per call)
๐Ÿ“ Clipboard (run I) Copying 10,000 x 5 values: Copy Destination:= 23 ms (fastest), PasteSpecial 26 ms, recorder style 32 ms, .Value2 = .Value2 35 ms: no speed cost

Note

Avoid the clipboard for its side effects, not for speed: it replaces what the user copied, fails when another program holds it, and leaves Excel in copy mode until Application.CutCopyMode = False. Copy Destination:= copies formats and formulas without the clipboard.

๐Ÿ“ PERF005 โ€” deleting rows in a loop

' โŒ the sheet shifts on every delete: 0.86 ms each
For r = LastRow To 2 Step -1
    If Ws.Cells(r, 1).Value2 = "X" Then Ws.Rows(r).Delete
Next r

' โœ… an isolated block of values: keep the rows you want in an array, write once
Dim Block As Range, Data As Variant, Kept() As Variant, r As Long, c As Long, k As Long
Set Block = Ws.Range("A2", Ws.Cells(LastRow, LastCol))
Data = Block.Value2
ReDim Kept(1 To UBound(Data, 1), 1 To UBound(Data, 2))
For r = 1 To UBound(Data, 1)
    If Data(r, 1) <> "X" Then
        k = k + 1
        For c = 1 To UBound(Data, 2)
            Kept(k, c) = Data(r, c)
        Next c
    End If
Next r
Block.ClearContents
If k > 0 Then Block.Resize(k).Value2 = Kept

๐Ÿ“ 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

Warning

Union and AutoFilter are not faster than the loop when the rows are scattered: Union of 2,500 areas was 3.5x slower. Use them only when the rows already form a few blocks. The array rebuild rewrites values in place: it fits only an isolated block of values. With formulas, row formatting or other columns on the same rows, sort so the rows to delete form one block and delete it in one call. A top-down For loop skips rows (๐Ÿ“ N N Y N N Y left N Y N Y).

๐Ÿ“ PERF007 โ€” lookups against a table, per row

VLookup and Match scan the table, so their cost grows with its size; Find is far slower still.

' โŒ rows x table
For RowIndex = 1 To UBound(Data, 1)
    Data(RowIndex, 2) = Application.VLookup(Data(RowIndex, 1), Table, 2, False)
Next RowIndex

' โœ… index the table once (first match wins, case-insensitive, like VLookup)
Dim Index As Object, TableData As Variant, T As Long
Set Index = CreateObject("Scripting.Dictionary")
Index.CompareMode = vbTextCompare
TableData = Table.Value2
For T = 1 To UBound(TableData, 1)
    If Not Index.Exists(TableData(T, 1)) Then Index.Add TableData(T, 1), TableData(T, 2)
Next T
For RowIndex = 1 To UBound(Data, 1)
    If Index.Exists(Data(RowIndex, 1)) Then
        Data(RowIndex, 2) = Index(Data(RowIndex, 1))
    Else
        Data(RowIndex, 2) = CVErr(xlErrNA)          ' what Application.VLookup returns
    End If
Next RowIndex
๐Ÿ“ Run J Exact VLookup: 12 us per lookup at 1,000 rows, 53 us at 10,000, 0.55 ms at 100,000 (half the keys missing)
๐Ÿ“ Run J Range.Find: 46-106x VLookup (0.57 ms to 58 ms per lookup)
๐Ÿ“ Run J Match(k, keys, 1) on sorted keys, then a check: 15 us at any size; one read and a binary search: the fastest up to 10,000 rows
๐Ÿ“ Run J Dictionary: building it costs about 1.4 us per row, so it pays off above about 250 lookups (3.3x faster at 1,000 lookups in 1,000 rows, 2.5x slower at 100 in 100,000)

๐Ÿ“ PERF012 โ€” whole columns

Data = Ws.Range("A:A").Value2                              ' โŒ 1,048,576 cells
Data = Ws.Range("A1", Ws.Cells(Ws.Rows.Count, 1).End(xlUp)).Value2   ' โœ… the used block
๐Ÿ“ Run I Reading 10,000 values and summing them in a loop to UBound: Range("A:A").Value2 63 ms, used block 1.5 ms (43x, read and scan timed together)
๐Ÿ“ Run I 200 Match and CountIf over A:A against the used block: same time. Excel stops at the used range: a whole column inside a worksheet function costs nothing

๐Ÿ“ PERF008 / PERF010 โ€” Evaluate, Calculate

' โŒ
For r = 1 To n
    Results(r) = Evaluate("SUM(A" & r & ":J" & r & ")")   ' parses a formula per row
    Ws.Calculate                                           ' recalculates per row
Next r

' โœ…
Ws.Calculate                                               ' once, after the loop
๐Ÿ“ Run J Evaluate per row 30-33 us, [B1] per row 30 us: 260-290x the same arithmetic in VBA; one array Evaluate over the block 1.4x
๐Ÿ“ Run J Application.Calculate after each of 300 writes: 11x once after the loop, 137x one block write; with 500 volatile UDF cells elsewhere, 13.5x more

Warning

๐Ÿ“ [A1] and Application.Evaluate read the active sheet. Range.Calculate leaves dependants outside the range stale; Worksheet.Calculate leaves volatile cells on other sheets stale.

๐Ÿ“ PERF013 โ€” volatile UDFs

' โŒ recalculates on every change anywhere in the workbook
Public Function RateFor(ByVal Tenor As Double) As Double
    Application.Volatile
    RateFor = ThisWorkbook.Worksheets("Curve").Range("B2").Value2 * Tenor
End Function

' โœ… every input is an argument, so Excel's dependency tree tracks it
Public Function RateFor(ByVal Tenor As Double, ByVal BaseRate As Double) As Double
    RateFor = BaseRate * Tenor
End Function
๐Ÿ“ Run J One write to an unrelated cell recalculated all 500 volatile UDF cells (0 when not volatile): about 10 us per cell, 5.1 ms per write, 103x
๐Ÿ“ Run J The same 500 cells with calculation manual during the writes and one Calculate at the end: 1.7x the non-volatile case

Warning

Removing Application.Volatile changes when the function recalculates: if it reads anything not passed as an argument, it will show stale values.

๐Ÿ“ PERF021 โ€” sheet writes without the state guards

๐Ÿ“ Run H One Range.Value of 5,000 x 8 values: 76 ms with ScreenUpdating on, 51 ms off (1.5x). Writing in one block matters far more (22x) than the guard
๐Ÿ“ Run I Formatting per row with ScreenUpdating on: 1.8x off
๐Ÿ“ Run J 1,000 writes feeding formulas, a change handler on: no guard 0.62 s; calculation manual alone 3.9x; ScreenUpdating or EnableEvents off alone 1.2x each; all three 17.5x; one block write 350x
๐Ÿ“ Run J The same with 500 volatile UDF cells on another sheet and no guard: 5.6 s, 9x

Turn calculation to manual first; it is the guard that pays. Restore all three on the clean exit and in the error handler (PERF022).

๐Ÿ“ PERF004 โ€” ReDim Preserve inside a loop

' โŒ copies the whole array on every pass
For i = 1 To n
    ReDim Preserve Items(1 To i)
    Items(i) = Value(i)
Next i

' โœ… grow by doubling, trim once at the end
Dim nItems As Long
ReDim Items(1 To 16)
For i = 1 To n
    If nItems = UBound(Items) Then ReDim Preserve Items(1 To 2 * UBound(Items))
    nItems = nItems + 1
    Items(nItems) = Value(i)
Next i
ReDim Preserve Items(1 To nItems)
๐Ÿ“ Run K Per item: 0.08-0.42 us, 2.4-6.7x sizing to the input and trimming once (10,000 and 100,000 items, Long and String, two machines); 10-40 ms in all for 100,000 items
๐Ÿ“ Run K Doubling and chunks of 1,000 within 1.5x of sizing once; a counting pass first 1.2-2x
๐Ÿ“ Run K Collection.Add, then a copy into an array: 4-6.5x, the slowest form

Not the quadratic cost it is said to be on 64-bit Excel: worth fixing in hot code, but MEDIUM rather than HIGH is the severity the figures support. Planned for v1.1.0 (#49): MEDIUM, and no finding for the doubling form, which the checker flags today. Sizing to an upper bound, such as the rows of the source, is the simplest fix.

๐Ÿ“ PERF025 โ€” a large array passed ByVal

' โŒ copies the whole table on every call from the loop
Private Function FindRow(ByVal Data As Variant, ByVal Key As String) As Long

' โœ… passes a reference; the callee only reads the table
Private Function FindRow(ByRef Data As Variant, ByVal Key As String) As Long
๐Ÿ“ Runs A, C 10,000 x 20 Variant array: 3.4 ms per call ByVal, 131 ns ByRef (26,000x); 100,000 calls spend about 340 s copying
๐Ÿ“ Run A 100,000-character String: 4.9 us ByVal, 48 ns ByRef (100x): no rule, small unless the strings are very long

The checker cannot know how large the array is, so the severity comes from how the parameter is used: HIGH when the procedure walks it (For ... To UBound(X)) or indexes it in 2-D and is called inside a loop in the same file; LOW for a 2-3 item tuple read by constant index or a procedure never called in a loop. In a scan of 18 public VBA projects, only 1 of 148 such parameters was a real cost (see Passing Data). Keep ByVal when the callee assigns into the array; then copy only what it changes.

๐Ÿ“ PERF020 / PERF024 / PERF018 โ€” output, loop conditions and IIf

' โŒ
For i = 1 To n
    Debug.Print i                                   ' writes to the Immediate window
    x = IIf(a(i) > 0, a(i), 0)                      ' evaluates both branches
Next i
Do While i <= UBound(a)                             ' UBound re-evaluated every pass
    i = i + 1
Loop

' โœ…
For i = 1 To n
    If a(i) > 0 Then x = a(i) Else x = 0
Next i
last = UBound(a)
Do While i <= last
    i = i + 1
Loop
๐Ÿ“ Run K Debug.Print per pass: 0.45-1.8 ms per line with the editor open, 10,700-24,000x; behind If on a False constant or inside #If: no cost
๐Ÿ“ Run K Application.StatusBar per pass: 62-72 us, 980-1,500x (no rule yet; planned for v1.1.0, #50)
๐Ÿ“ Run K Do While i <= UBound(a) or Len(s): at most 4 ns per pass; col.Count 2x; late-bound d.Count 17-26x; End(xlUp) 7 us, UsedRange 0.21 ms per pass
๐Ÿ“ Run K IIf: 3.2-3.7x If, about 0.1 us per call; with a function in the other branch, 2.8-2.9x, as it runs every time

PERF020 is LOW today, yet one line costs of the order of a row delete: MEDIUM is planned for v1.1.0 (#49), HIGH if the cost with the editor closed proves close (not yet measured). PERF024 matters only when the condition calls into Excel or a late-bound object; UBound and Len are not worth a finding. IIf stays LOW: replace it because both branches run (see Correctness Traps).

๐Ÿ—บ๏ธ Measurement plan

Run Covers Status
H CSV read and decode, parsing, one Range.Value with ScreenUpdating on and off, per-row and per-cell writes, export (M_BookBench7.bas) โœ… done
I PERF002 at three sizes, .Value against .Value2, formatting; PERF001 / PERF006 clipboard; PERF005 row deletes; PERF012 whole columns (M_BookBench8.bas) โœ… done
J PERF007 lookups against table size; PERF008 Evaluate; PERF010 Calculate; PERF013 volatile UDFs; PERF021 state guards with formulas and events (M_BookBench9.bas, cBench9Events.cls) โœ… done
K PERF004 ReDim Preserve; PERF020 Debug.Print and the status bar; PERF024 loop conditions; PERF018 IIf; PERF011 other objects (M_BookBench10.bas) โœ… done
L Cross-process calls, ADO, UserForm lists and arithmetic (#53) ๐Ÿ—“๏ธ planned

Each run follows the Measurement Method, and each result moves its rule from ๐Ÿงช to ๐Ÿ“ on this page.

โšก VBA Performance

Topics

Reference

Clone this wiki locally