Make your own free website on
Write Your First Visual Basic Program

Lesson 2
Tutorials - Page 1 - Page 2 - Page 3 - Page 4 - Page 5 - Page 6 - Page 7 - Page 8 - Page 9 - Page 10 - Page 11 - Page 12 - Page 13

Scope of Variables (Continue)
As you saw in the previous page,
If you declare variable in a sub, it exist only
within the sub.

To declare variable that will be exist in all subs,
you have to declare it in the "Declarations area" of your code.
Choose "(General)" From the components List in the code window (Figure 1).

Figure 1

Put the gogo declaration statement in the "Declarations area".
Simply write:

Dim gogo As Integer

And delete the old statement that found
in the Command1_Click event.

After you've done so, your code should look like this:

Dim gogo As Integer

Private Sub Command1_Click()
    gogo = 100
End Sub

Private Sub Command2_Click()
    MsgBox gogo
End Sub

Now the gogo variable is being declared in the Declarations area
of your code, and should be available from every part of your code.

Lets check it out:
Run the program.
The gogo variable is being declared immediately when the
program is being started.

Press the Command2 Button.
A message box with the number 0 is popping.
It is because the gogo variable has been declared, but
we didn't assign any value to it yet, so right now its value
is the default value - 0.

Press the Command1 Button.
The value 100 is being assigned to the gogo variable.

Press the Command2 Button - a message box
with the value 100 is popping.

Back  Forward