Make your own free website on Tripod.com
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
Insert two Command Buttons to your form (with
the names Command1 and Command2),
and Add the following code to your program:


Private Sub Command1_Click()
    Dim gogo As Integer
    gogo = 100
End Sub

Private Sub Command2_Click()
    MsgBox gogo
End Sub



Run the program, and click on the Command1 button.
the code that found in the Command1_Click event will be executed.
The gogo variable will be declared, and it will store the value 10.

Now press on the Command2 button.
In result, the   MsgBox gogo    Line will be executed.
But instead of displaying the value of the gogo variable (100),
It shows nothing, like if the gogo variable hasn't been declared at all!

The reason for all of this, is the scope of the variable.
Every variable that been declared, "Exist" only in the
Sub or function that he was declared in.

What is Sub? (We will learn about functions later)
Sub is a Block of code that starts with  Sub  and
ends with   End Sub
Every event is a sub, because it begins with   Sub   and
ends with   End Sub

For Example:

Private Sub Command1_Click()
    MsgBox "Hello"
End Sub


Every line of code that found between the     Sub Command1_Click()
and the    End Sub    is belong to the sub Command1_Click()

So because we've declared the gogo variable in the
Commad1_Click event, it's declared only within the sub, and
it's not declared in the Command2_Click event.


So if you want that a specific variable will be "exist" in
your whole program, no matter from which sub you call it,
what can you do?
The Answer is in the next page...

Back  Forward