Scope Rules
◄Summary► ◄Details► ◄Contents► ◄Index► ◄Back►
──────────────────────────────────────────────────────────────────────────────
Scope Rules
■ Visual Basic follows a set of scope rules that defines the range over
which a variable value is accessed. In general, a variable can have one of
two scopes, global and local:
• Global values can be accessed from anywhere in the project
• Local values can only be accessed from the location where it is declared
■ Visual Basic also supports an area of variable scoping that falls between
local and global:
┌───────────────────────────────────────────────────────────────────────┐
│ Local ←░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░→ Global │
└───────────────────────────────────────────────────────────────────────┘
■ This area includes variable scope where:
*A* The value may be accessed at the module level or in any SUB procedure
within the module
*B* The value may be accessed at the module level only in a multiple-
module project
░┌─────*A*──────┐░┌─────────────*B*──────────────┐░
░│ MODULE.BAS │░│┌─────────────┐┌─────────────┐│░
░│- - - - - - - │░││ ││ ││░
(to local)◄─░│ SUB Jones () │░││ MODULE1.BAS ││ MODULE2.BAS ││░─►(to global)
░│- - - - - - - │░││ ││ ││░
░│ SUB James () │░│└─────────────┘└─────────────┘│░
░└──────────────┘░└──────────────────────────────┘░
■ In Visual Basic, the placement and use of six different statements
determine the scope of a variable:
Statement Variable Access
════════════ ═════════════════════════════════════════════════════════
DIM Local to module or procedure where declared (local)
DIM SHARED Shared between the module where declared and any SUB
procedures contained within the module (*A*). Duplicate
DIM SHARED statements must appear in the Declarations
section of the module.
See: ◄DIM Statement►
SHARED Shared between the procedures where declared and the
module level where they are contained (*A*). Similar
to DIM SHARED, except duplicate SHARED statements must
appear in the Declarations section of each procedure
within the module. See: ◄SHARED Statement►
COMMON Shared between multiple modules at the module level only
(*B*). Duplicate COMMON statements must appear in the
Declarations section of each module.
COMMON SHARED Shared between multiple modules and all their procedures
(global). Duplicate COMMON SHARED statements must appear
in the Declarations section of each module.
See: ◄COMMON Statement►
$FORM Shared between multiple modules (form properties only).
$FORM statements must appear in the Declarations section
of each module from which you want to access another
form's properties. See: ◄$FORM Metacommand►
See Also
◄Array Storage Summary► ◄Variables Summary►