Static Variables
Suppose you have a Sub in a form called CountThem that looks like this:
Private Sub CountThem()
Dim intI As Integer
Static intJ As Integer
intI = intI + 1
intJ = intJ + 1
Print intI, intJ
End Sub
Suppose you have some other Sub that calls CountThem three times in a row:
Call CountThem
Call CountThem
Call CountThem
The following output would be displayed on the form (by default, the "Print" statement directs its output to the current form):
(values for intI) |
(values for intJ) |
1 |
1 |
1 |
2 |
1 |
3 |
Note that the "regular" variable, intI, declared with "Dim", does not retain its value between calls, whereas the Static variable, intJ, does.
Note: The keyword "Static" can also be used in the Sub procedure header, which causes all variables in that procedure to be static. Example:
Private Static Sub AllVarsAreStatic()
Dim intCounter As Integer ' as if declared Static
Dim strErrMsg As String ' as if declared Static
. . . ' other statements
End Sub