Wauvel

Excel like a finance pro.

← The library

VBA · Syntax

ByVal and ByRef

ByRef (the default) lets a procedure change the caller's variable; ByVal passes a copy.

OccasionalDifficulty 1350 · Advanced
Practice · 2 questions →

When to use it

Arguments are passed ByRef by default, so a procedure can change the caller's variable. ByVal passes a copy, which is safer when the procedure should not affect its inputs.

The code

Code
Sub Bump(ByRef n As Long)
  n = n + 1
End Sub

Worked examples

  • ByRef

    Sub Bump(ByRef n As Long) n = n + 1 End Sub ' after Bump x, x is one larger The caller's variable changes

    ByRef shares the variable.

  • ByVal

    Sub Show(ByVal n As Long) n = n + 1 End Sub ' the caller's x is unchanged A copy is changed, not the original

    ByVal protects the caller.

  • Force ByVal

    Call Bump((x)) Extra parentheses force ByVal for one call

    A quirk worth knowing.

Worth knowing

  • Use ByVal for values you only read; use ByRef to return several results.
  • Objects are always references; ByVal on an object only protects the variable, not the object.
  • Event signatures dictate ByVal Target As Range; do not change them.

Where it goes wrong

  • Accidental ByRef changes callers' variables mysteriously.
  • Parentheses around a single argument in a Call silently switch to ByVal.

Related

Learn the moves here — or let Wauvel run them on your numbers.

Meet your AI CFO →

One CFO-grade Excel tip a week

A short, practical email for finance operators — functions, shortcuts, and the moves that save an afternoon. Free, unsubscribe anytime.