Nov 05 2020 02:32 PM
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?
Nov 05 2020 02:44 PM
SolutionWithin 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.
Nov 05 2020 03:32 PM
@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."
Nov 05 2020 02:44 PM
SolutionWithin 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.