Variable Scope for Visual Basic 6.0 Users
Visual Basic 2005 updates local variable scope to support block scope and improve structured programming.
Visual Basic 6.0
In Visual Basic 6.0, any variable declared inside a procedure has procedure scope, so it can be accessed anywhere else within the same procedure. If the variable is declared inside a block — that is, a set of statements terminated by an End, Loop, or Next statement — the variable is still accessible outside the block.
The following example illustrates procedure scope, where the block is a For loop:
For I = 1 To 10
Dim N As Long = 0
' N has procedure scope although it was declared within a block.
N = N + Incr(I)
W = Base ^ N
' N is still visible outside the block it is declared in.
Visual Basic 2005
In Visual Basic 2005, a variable declared inside a block has block scope, and it is not accessible outside the block. The preceding example can be rewritten as follows:
Dim N As Long = 0 ' N is declared outside the block and has procedure scope. For I As Integer = 1 To 10 ' I is declared by the For statement and therefore within the block. N = N + Incr(I) Next I w = Base ^ N ' N is visible outside the block but I is not.
Because the For statement declares I as part of the For block, I has block scope only.
However, a variable's lifetime is still that of the entire procedure. This is true whether the variable has block scope or procedure scope. If you declare a variable inside a block, and if you enter that block several times during the lifetime of the procedure, you should initialize the variable to avoid unexpected values.