Teasel
Teasel

Reputation: 1340

Default value for non-existing variable

I was working on a VBA excel-based project and made a typo while calling a variable. After trying to debug the function for a while, I realised I was making a reference to a non-existing variable (because of the typo) and yet the debugger didn't indicate the issue.

I tried to get the value of the variable and the result was empty. I tried to do a comparison with the variable and it was returning false every time.

I'd like to know if it has something to do with the Boolean default value which is False (as said by Microsoft for the VB language here)? And if it's the case, why is it printing no value?

Also, why did the debugger indicate no issue?

Sub MySub()
    'Print absolutely nothing
    Debug.Print myVariable

    If (myVariable) Then
        Debug.Print "Condition is true"
    Else
        'The condition always comes in that
        Debug.Print "Condition is false"
    End If
End Sub

Upvotes: 1

Views: 245

Answers (1)

Scott Craner
Scott Craner

Reputation: 152505

If you do not declare the variable, it is assumed to be variant and the natural state of a variant is Empty.

Actually the first line is printing a blank line in the Immediate window since it is empty.

When it is first used as you have VBA assumes you wanted to use it as Boolean and therefor it changes to a Boolean and the base or empty value of a boolean is False.

Sub MySub()

    Debug.Print myVariable 'Prints and empty line As the variable is Empty Variant

    If (myVariable) Then 'Treated as a Boolean with value False empty = false
        Debug.Print "Condition is true"
    Else
        'This fires as base boolean value is False
        Debug.Print "Condition is false"
    End If
End Sub

enter image description here

If you want an error to pop up then use Option Explicit at the top of the module or set that as default in the settings.

To set it as the default go to Tools ==> Options and click Require Variable Declaration

enter image description here

enter image description here

Upvotes: 7

Related Questions