In VBA (Visual Basic for Applications), the Static statement is used to declare local variables in a procedure (Sub or Function) in a way that their values are preserved between calls to the procedure. Unlike regular local variables, which lose their value as soon as the procedure ends, Static variables retain their value between multiple calls of the same procedure.
Here’s how to use the Static statement:
Basic Syntax
To declare a static variable within a procedure, you use the Static keyword followed by the variable declaration:VBA
In this example, myVariable is a static variable of type Integer.
Sub MyProcedure()
Static myVariable As Integer
' Rest of the code
End Sub
Example Usage
Suppose you have a function that counts how many times it has been called:VBA
Each time CountCalls is called, callCount is incremented by 1, and its value is retained for the next call.
Function CountCalls() As Integer
Static callCount As Integer
callCount = callCount + 1
CountCalls = callCount
End Function
Scope of Static Variables
- The scope of a Static variable is local to the procedure in which it is declared. This means it is not accessible from other procedures.
- However, its lifetime is the same as that of the program, so it retains its value between calls until the program ends or the workbook is closed.
Static Variables vs. Module-Level Variables:
- A Static variable in a procedure is a good choice when you need to retain a value between calls to that procedure, but you don’t need the variable to be accessible from other procedures in the module.
- If you need a variable to be accessible from multiple procedures within the same module, consider using a module-level variable (declared outside of any procedure with Dim or Private at the top of the module).