VB 6 Variable Scope

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.

Advertisements

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:

  1. Module Level with Public (Global)
  2. Form or Module level (Global only to the Module).
  3. 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.

Global Declaration using Public
Figure 1 – Global Declaration using Public

Form Or Module Level

Advertisements

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.

Form Level Global Declarations
Figure 2 – Form Level Global Declarations using Dim Statement.

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:

Local Variable Declaration
Figure 3 – Local Variable Declaration

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.

Advertisements

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.