Skip to content

Passing Data

Daniele Penza edited this page Dec 2, 2026 · 3 revisions

πŸ“¦ Passing Data

Evidence Top cost

πŸ”΄ Large arrays passed ByVal

πŸ“ A 10,000 x 20 Variant array passed ByVal costs 3.4 ms per call: VBA copies the whole array every time. ByRef costs 131 ns. Over 100,000 calls that is about 340 s against 0.01 s. The VBA Performance Manager confirmed the copy cost (3.5 ms).

' ❌ copies the whole table on every call
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

Important

In a scan of 18 public VBA projects, 148 ByVal Variant parameters were indexed as arrays, but only one was a real cost: a lookup helper that received a whole table ByVal and was called inside a loop. Most were two- or three-element tuples, where the copy is negligible. The cost needs both a large array and many calls.

The checker reports this shape as PERF025: HIGH when the procedure walks the array or indexes it in 2-D and is called inside a loop in the same file, LOW otherwise (Skill Rules).

🟠 Long strings passed ByVal

πŸ“ A 100,000-character String passed ByVal: 4.9 us per call, 100x ByRef.

' ❌
Private Function CountFields(ByVal Line As String) As Long
' βœ… when the callee does not change Line
Private Function CountFields(ByRef Line As String) As Long

⚠️ Traps

Trap Evidence What to do
A class's Public field passed ByRef πŸ“ Increment obj.Number left Number at 0: the field is a hidden property pair, so the callee changes a copy Copy to a local, pass the local, assign back
ByVal on an object The callee still changes the object's properties: only the reference is copied Do not rely on ByVal to protect an object
Switching a ByVal parameter to ByRef The callee may now change the caller's variable Switch only where the callee does not assign to it
Dim tmp As Long
tmp = obj.Number
Increment tmp          ' ByRef works on the local
obj.Number = tmp

🟒 Not worth changing

Advice Result
Assign a function's result array as its last statement πŸ“ no difference (1%) on 100,000 Double
ByVal for a Long or Double No measurable difference either way

⚑ VBA Performance

Topics

Reference

Clone this wiki locally