SOLVED

Scope of declarations in VBA

Brass Contributor

I'm relatively new to VBA.  I was surprised to get a duplicate declaration error from this code:

 

    If False Then

        Dim j As Integer

    Else

        Dim j As Integer

    End If

 

In other languages I'm familiar with, if and else define local scopes. Does VBA really consider these two declarations to be within the same scope?

2 Replies
best response confirmed by perkin_warbeck (Brass Contributor)
Solution

@perkin_warbeck 

Within a procedure or function, each variable can only be declared once.

Each private variable can only be declared once in a standard or class module.

Each public variable can only e declared once across all standard modules.

 

There is an exception: you can define so-called compiler constants. See #Const directive and #If...Then...#Else directive 

 

Example:

 

#Const TestVersion = True

#If TestVersion Then
    Dim x As Long
#Else
    Dim x As String
#End If

 

Please note that you can only define compiler constants, not compiler variables.

@Hans Vogelaar Thanks for your answer.  I'm surprised I hit this error for the first time today, after writing thousands of lines of VBA code over the last six months.  I'm a big believer in local scoping of variables. From now on I will refer to VBA a "so-called programming language."

1 best response

Accepted Solutions
best response confirmed by perkin_warbeck (Brass Contributor)
Solution

@perkin_warbeck 

Within a procedure or function, each variable can only be declared once.

Each private variable can only be declared once in a standard or class module.

Each public variable can only e declared once across all standard modules.

 

There is an exception: you can define so-called compiler constants. See #Const directive and #If...Then...#Else directive 

 

Example:

 

#Const TestVersion = True

#If TestVersion Then
    Dim x As Long
#Else
    Dim x As String
#End If

 

Please note that you can only define compiler constants, not compiler variables.

View solution in original post