Ans
Ans

Reputation: 1234

Duplicate declaration in the current scope error; two loops with the same variable, variable scope

I have this code: there are two for loops from 1 to 10 in it. In each loop a variable k is declared.

Sub Test()
    Dim i As Long
    For i = 1 To 10
        Dim k As Long
        k = i * 2

        Debug.Print k
    Next


    Dim j As Long
    For j = 1 To 10
        Dim k As Long  'error here
        k = j * 2

        Debug.Print k
    Next

End Sub

However when I try to run it I get a duplicate declaration in the current scope error. I'm not sure why I get it - isn't a variable's scope limited by the loop, since it was declared within it? Is there any way to remove the remnants of the first variable so that it would be possible to create a variable with the same name in the second loop?

Upvotes: 1

Views: 618

Answers (1)

user8753746
user8753746

Reputation:

When you declare a variable in a procedure, this variable is valid for all the procedure, not only for the loops. If you want to clear your variable, you can set k = 0

When a local variable is declared with the Dim statement, the variable remains in existence only as long as the procedure in which it is declared is running. Usually, when the procedure is finished running, the values of the procedure's local variables are not preserved, and the memory allocated to those variables is released. The next time the procedure is executed, all of its local variables are reinitialized.

https://support.microsoft.com/en-us/help/141693/scope-of-variables-in-visual-basic-for-applications

http://www.excel-easy.com/vba/examples/variable-scope.html

Upvotes: 2

Related Questions