user614244
user614244

Reputation: 33

VBA duplicated declaration in "if...else"

Simple as below:

If 1 = 2 Then
    Dim i As Integer  
Else
    Dim i As Integer
End If

This will give an error as "duplicated declaration in current scope". Why?

Upvotes: 3

Views: 5089

Answers (3)

Nilpo
Nilpo

Reputation: 4816

As mentioned, you cannot have more than one Dim statement for a variable with the same scope. Aside from that, however, why would you want to? Take your code for example.

If 1 = 2 Then 
    Dim i As Integer   
Else 
    Dim i As Integer 
End If 

The purpose of a conditional block is to execute two different pieces of code under two different circumstances. If you are declaring the same variable either way, there is no need for the conditional block at all. In all likelihood, it should probably be moved before the conditional.

Upvotes: -1

Drew Gaynor
Drew Gaynor

Reputation: 8482

In VBA, declarations of two variables with the same name cannot be made in the same procedure. See this article for more information: Duplicate declaration in current scope.

In your case, the "current scope" is the current procedure. The if and else blocks share the same scope.

For example, the following will give the same error even though the second declaration is unreachable:

Sub ErrorSub()
    Dim i As Integer

    If False Then
        Dim i As Integer
    End If
End Sub

But the following is perfectly valid and will work fine:

Sub MySub()
    Dim i As Integer
    i = 4
    MsgBox i
End Sub

Sub MyOtherSub()
    Dim i As Integer
    i = 3
    MsgBox i
End Sub

Sub CallSubs()
    MySub
    MyOtherSub
End Sub

Upvotes: 1

AMissico
AMissico

Reputation: 21684

Variables are local to the sub/function (procedure). In your case, the "current scope". VB, VBA, and VBScript do not have the concept of code blocks within a procedure. If I remember correctly, the only code blocks are modules, classes, forms (which are classes), and procedures.

You can declare a variable anywhere within the procedure as a convenience. Yet, the "current scope" is the procedure.

It was a design decision to make the language easier to use for B-eginners.


Duplicate declaration in current scope

The specified name is already used at this level of scope. For example, two variables can have the same name if they are defined in different procedures, but not if they are defined within the same procedure.

Inserted from http://msdn.microsoft.com/en-us/library/gg251613.aspx

Upvotes: 8

Related Questions