This article was previously published under Q119737
Retired KB Content Disclaimer
This article was written about products for which Microsoft no longer offers support. Therefore, this article is offered "as is" and will no longer be updated.
Normally in Visual Basic, when a static variable is declared inside aFunction or Sub procedure, it gets initialized to 0 (numeric data type) oran empty string, "" (string data type), by default. This article shows away to initialize these variables to values other than the default.
When a variant variable is first declared, it is initialized with the EMPTYvalue by default. The idea here is to take advantage of this fact, bytesting a dummy variant static variable with the IsEmpty function andinitializing the other static variables to the values you want if thisfunction returns TRUE. It is important to set the dummy variant to somevalue after you initialize your static variables, so that IsEmpty alwaysreturns FALSE for subsequent calls to the subroutine, and that because ofthis the other static variables are not reinitialized.
Here is an example that shows how to initialize a static variant, integer,and string variable declared in a Sub called InitStatic:
Start a new project in Visual Basic. Form1 is created by default.
On Form1, add a command button (Command1).
Add the following code to the "(general) (declarations)" section of Form1:
Sub initstatic () Static Dummy, V, I As Integer, S As String ' The code in the following if statement will be executed only once: If IsEmpty(Dummy) Then ' Initialize the dummy variant, so that IsEmpty returns FALSE for ' subsequent calls. Dummy = 0 ' Initialize the other static variables. V = "Great" I = 7 S = "Visual Basic" End If Print "V="; V, "I="; I, "S="; S ' Static variables will retain their values over calls when changed. V = 7 I = I + 7 S = Right$(S, 5) End Sub
Add the following code to the Command1_Click() event:
Sub Command1_Click() initstatic End Sub
Run the program (press the F5 key). Then double-click the Command1 button to see the results.