The scope of a VB 6 variable decides the lifetime of that variable. There are 3 levels of scope for a variable in Visual Basic 6. In this article, you will learn about the scope of variables with examples in a Visual Basic 6 project.
Level of Scope
The scope in many programming languages is either a global scope or a local scope. We will list out the global scope and local scope for a variable in visual basic 6.
Visual Basic 6 has 3 levels of scope:
- Module Level with Public (Global)
- Form or Module level (Global only to the Module).
- Procedure Level (Local scope)
Module Level With Public
Variables declared in the general section of the code editor using keyword Public are visible in all forms and modules throughout the VB 6 Project.
Example:
In this example, we declared two variable – test and number – as integers in the (General) section of Module 1. These integers will be available throughout the project and you can manipulate as and when necessary.
Form Or Module Level
In this level, the variable is declared under (General) section of Visual Basic code editor. The keywords – Dim
, ReDim
, Static
and Private
are used to declare the variables.
Example:
In the example below, the form name is “Accounting” and we have declared two variable using Dim statement. The scope of these variables is limited to the form only.
Procedure-Level
Each procedure in VB 6 has its own variables. Those variables are local to the procedure, and cannot be used elsewhere. The keyword – Public
cannot be used for procedures.
Example:
In the example above, the variable Number
is local to the procedure Form_Load( ).
This is because Form_Load ( )
procedure is by default a Private
procedure. This form assigns a value of 1003 to variable Number
when the form loads.