A Variable’s Scope : The scope of a variable is the section of the application that can see and manipulate the variable. If a variable is declared within a procedure, only the code in the specific procedure has access to that variable. When the variable’s scope is limited to a procedure it’s called local.
Private Sub Command1_Click()
Dim i as Integer
Dim Sum as Integer
For i=0 to 100 Step 2
Sum = Sum +i
MsgBox “ The Sum is “& Sum
A variable whose value is available to all procedures within the same Form or Module are called Form-wide or Module-wide and can be accessed from within all procedures in a component. In some situations the entire application must access a certain variable. Such variable must be declared as Public.
Lifetime of a Variable : It is the period for which they retain their value. Variables declared as Public exist for the lifetime of the application. Local variables, declared within procedures with the Dim or Private statement, live as long as the procedure.
You can force a local variable to preserve its value between procedure calls with the Static keyword. The advantage of using static variables is that they help you minimize the number of total variables in the application.
Variables declared in a Form outside any procedure take effect when the Form is loaded and cease to exist when the Form is unloaded. If the Form is loaded again, its variables are initialized, as if it’s being loaded for the first time.