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?
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.
Subscribe to email feed



