Static variables in VBA are quite simple:
Public Sub foo() Static i As Integer i = i + 1 Debug.Print i End Sub
(when called several times):
1 2 3 ...
The problem is that VBA does not support initializing a variable on the same line as the declaration (not counting with : to put two lines on one):
Public Sub foo() Dim i As Integer = 5 'won't compile! Dim j As Integer j = 5 'we have to do this instead End Sub
This is a collision with static variables:
Public Sub foo() Static i As Integer 'we can't put an initial value here... i = 5 'so this is how we'd usually initialize it, but... i = i + 1 Debug.Print i End Sub
You can probably see what is happening. The very first thing that a variable does each time foo called returns to 5. Exit:
6 6 6 ...
How can you initialize a static variable in VBA to a value other than the default? Or is it just a VBA throwing a ball?
source share