Static Variables

The local variables of a procedure are initialized every time it is invoked. All numerical variables will be set to 0, and all string variables will be set to a zero-length string.

However, sometimes you may want to invoke a procedure several times and have it retain the values of its local variables.

This can be done using static variables. The static statement is designed to define the local variables that you want to retain their values between invocations.

A simplified version of the syntax of this statement is:

Static variable1Name, variable2Name

This defines two variables variable1Name and variable2Name as Static variables. One can define as many static variables as needed.

Here is an example of its use:

Sub TestStatic()
a = 15
c = Accumulate(a)
MsgBox c
MsgBox Accumulate(28)
End Sub

Function Accumulate(n)
Static sum
Sum = sum + n
Accumulate = sum
End Function

One the first invocation, a value of 15 is passed to procedure Accumulate. Since this is the first time the function is called, the static variable sum has an initial value of 0. Therefore, the addition yields 15. This result is passed back to the main Sub, assigned to c, and the message box displays the result: 15.

One the second invocation, a value of 28 is passed to the function Accumulate. Because of the Static statement, sum has retained it previous value of 15. Therefore, the addition yields 43, which is passed back and then displayed as: 43.