Software Development optimize

Preserve procedure variables with Static in VB6

In order to make a Visual Basic procedure remember the value of local variables between calls, try using the Static keyword. Peter Aitken demonstrates the benefits of using Static.

By default in Visual Basic, local variables—those declared inside a procedure—are re-initialized each time the procedure is called. Number variables are initialized to 0 and string variables are initialized to a blank string. For example, here's a normal function:

Private Function Foo() As Single

Dim val As Single

val = val + 1
Foo = val

End Function

If you call it five times, the return value will be 1 each time because the local variable val is initialized to 0 and then has 1 added. You can make a procedure remember the value of local variables between calls with the Static keyword. For example:

Private Function Foo() As Single

Static val As Single

val = val + 1
Foo = val

End Function

Now, if you call it five times, the return values will be 1, 2, 3, 4, and 5.

Using Static in the local variable declaration as shown above lets you define individual variables as static; the procedure can also have regular non-static local variables. You can also use Static in the procedure definition to make all of its local variables static, like this:

Private Static Function Foo() As Single

Dim val As Single

val = val + 1
Foo = val

End Function

Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically sign up today!

0 comments