Variable Scopes
Some aspects of scoping in Basic depend on the library structure. This section describes which variables declared in a Basic source code module are seen from what libraries or modules. Generally, only variables declared outside Subs are affected by this issue. Variables declared inside Subs are local to the Sub and not accessible from outside of the Sub. For example:
Option Explicit ' Forces declaration of variables
Sub Main
Dim a%
a% = 42 ' Ok
NotMain()
End Sub
Sub NotMain
a% = 42 ' Runtime Error "Variable not defined"
End Sub
Variables can also be declared outside of Subs. Then their scope includes at least the module they are declared in. To declare variables outside the Subs, the commands Private
, Public/Dim
and Global
are used.
The Private
command is used to declare variables that can only be used locally in a module. If the same variable is declared as Private
in two different modules, they are used independently in each module. For example:
Library Standard, Module1:
Private x As Double
Sub Main
x = 47.11 ' Initialize x of Module1
Module2_InitX ' Initialize x of Module2
MsgBox x ' Displays the x of Module1
Module2_ShowX ' Displays the x of Module2
End Sub
Library Standard, Module2:
Private x As Double
Sub Module2_InitX
x = 47.12 ' Initialize x of Module2
End Sub
Sub Module2_ShowX
MsgBox x ' Displays the x of Module2
End Sub
When Main
in Module1 is executed, 47.11
is displayed (x
of Module1) and then 47.12
(x
of Module2).
The Public
and Dim
commands declare variables that can also be accessed from outside the module. They are identical in this context. Variables declared with Public
and Dim
can be accessed from all modules that belong to the same library container. For example, based on the library structure shown in Illustration 12.39: Sample module structure, any variable declared with Public
and Dim
in the Application Basic Modules Standard/Module1, Standard/Module2, Library1/Module1, Library1/Module2 can also be accessed from all of these modules, therefore the library container represents the logical root scope.
Content on this page is licensed under the Public Documentation License (PDL). |