A variable’s scope determines which other pieces of code can access it. For example, if you declare a variable inside a subroutine, only code within that subroutine can access the variable. The four possible levels of scope are (in increasing size of scope) block, procedure, module, and namespace.

Block Scope

A block is a series of statements enclosed in a construct that ends with some sort of End, Else, Loop, or Next statement. If you declare a variable within a block of code, the variable has block scope, and only other code within that block can access the variable. Furthermore, only code that appears after the variable’s declaration can see the variable.

Variables declared in the block’s opening statement are also part of the block. Note that a variable is visible within any sub-block contained within the variable’s scope.

For example, consider the following code snippet:

For i As Integer = 1 To 5
    Dim j As Integer = 3
    If i = j Then
         Dim M As Integer = i + j
         Debug.WriteLine("M: " & M)
         Dim N As Integer = i * j
         Debug.WriteLine("N: " & N)
    End If
    Dim k As Integer = 123
    Debug.WriteLine("k: " & k)
Next i

This code uses a For loop with the looping variable i declared in the For statement. The scope of variable i is block-defined by the For loop. Code inside the loop can see variable i, but code outside of the loop cannot.

Inside the loop, the code declares variable j. This variable’s scope is also the For loop’s block.

If i equals j, the program declares variable M and uses ...

Get Visual Basic 2012 Programmer's Reference now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.