Wauvel

Excel like a finance pro.

← The library

VBA · Variables

Static variables

A local variable that keeps its value between calls.

Rarely usedDifficulty 1300 · Proficient
Practice · 2 questions →

When to use it

Static declares a local variable that keeps its value between calls to the procedure, unlike Dim which resets each time.

The code

Code
Static calls As Long
calls = calls + 1

Worked examples

  • Call counter

    Static calls As Long calls = calls + 1 MsgBox calls Counts how many times the procedure has run

    A per-procedure counter.

  • Lazy initialization

    Static cache As Object If cache Is Nothing Then Set cache = CreateObject("Scripting.Dictionary") Builds an expensive object once

    Caching.

  • Whole procedure

    Static Sub Toggle() Every local in the procedure is Static

    Rarely useful.

Worth knowing

  • Module-level variables achieve the same with wider visibility; Static keeps it private to the procedure.
  • Values reset when the workbook closes or code is reset.
  • Good for toggles and counters in event handlers.

Where it goes wrong

  • Easy to forget the value persists, which makes tests behave differently on second run.
  • Reset by any edit to the code.

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.