What are local variables vs. global variables?
Variables declared in a Visual Basic program are visible (i.e., they can be referenced) inside the "scope" where they are defined. The scope is the program unit inside of which the variable is defined. For example, variables declared inside a subroutine are only visible inside that subroutine. Variables declared outside any routines, before any program code, are visible to all subroutines and functions in the same file. In the programs shown below, variable a is either defined inside the Main routine, and then must be passed to the subroutine that displays its value, or it is declared as a global variable, outside the Main routine, in which case it is visible in all subroutines and functions in the same file.
Here is a simple program, where the variable must be passed, because it is defined only inside the scope of the Main program.
Sub Main
Dim a As Long a=1 DisplayVariableA a
End Sub
Sub DisplayVariableA (a As Long)
MsgBox Str(a)
End Sub
Here is the functionally identical program, where the variable is declared globally.
Dim a As Long
Sub Main
a=1 DisplayVariableA
End Sub
Sub DisplayVariableA
MsgBox Str(a)
End Sub