Initializing Local Variables
Although Visual Basic gives you no direct help, it does give you two roundabout ways to initialize variables. The first technique takes advantage of the default initialization to 0, Empty, or Nothing.
If you can rule out the empty string as a valid value for a particular string variable, you can assume that the variable is uninitialized when it has this value. The same goes for 0 and numeric variables. For example:
Sub InitializeMe()
Static sNeverEmpty As String, iNeverZero As Integer
If sNeverEmpty = sEmpty Then sNeverEmpty = “Default”
If iNeverZero = 0 Then iNeverZero = -1
§
End Sub
Of course, if sNeverEmpty can be changed by some other code, and if sEmpty is a valid value, this code won’t work because sNeverEmpty will be randomly changed to “Default” under certain circumstances. It’s easy to imagine lots of string variables that should never be empty, but it’s harder to think of integer variables that should never be 0.
Notice that the variables in question are static so that they retain the initialized value across calls. You don’t need any special initialization code if the variable is reinitialized every time you enter the procedure:
Sub InitializeMe()
Dim sNeverEmpty As String, iNeverZero As Integer
sNeverEmpty = “Default”: iNeverZero = -1
If 0 is valid for your numeric values or sEmpty is valid for your strings, you must create a variable specifically for testing:
Sub InitializeMe()
Static fNotFirstTime As Boolean
Static sAnyValue As String, iAnyValue As Integer
If Not fNotFirstTime Then
fNotFirstTime = True
sAnyValue = “First time”: iAnyValue = 1
End If
§
The double negative makes the code look more complex than it is. Things would be so much clearer if you could initialize the test variable to True:
Sub InitializeMe()
Static fFirstTime As Boolean = True
Static sAnyValue As String, iAnyValue As Integer
If fFirstTime Then
fFirstTime = False
sAnyValue = “First time”: iAnyValue = 1
End If
§
But if you could initialize fFirstTime to True, you wouldn’t need it because you could initialize sAnyValue and iAnyValue the same way.
You can use the same principle on global and module-level variables. The IsMissing function works with optional parameters in the same way. I’ll show you some related tricks later.