Variables are the memory
locations which are used to store values temporarily. A defined naming strategy
has to be followed while naming a variable. A variable name must begin with an
alphabet letter and should not exceed 255 characters. It must be unique within
the same scope. It should not contain any special character like %, &, !,
#, @ or $.
There are many ways of declaring variables in Visual Basic. Depending on where the variables are declared and how they are declared,
we can determine how they can be used by our application. The different ways of
declaring variables in Visual Basic are listed below and elucidated in this section.
Declaring a variable tells Visual Basic to reserve space in memory. It is not
must that a variable should be declared before using it. Automatically whenever
Visual Basic encounters a new variable, it assigns the default variable type and
value. This is called implicit declaration. Though this type of declaration is
easier for the user, to have more control over the variables, it is advisable
to declare them explicitly. The variables are declared with a Dim statement to
name the variable and its type. The As type clause in the Dim statement allows
to define the data type or object type of the variable. This is called explicit
Dim variable [As Type]
Dim strName As String
Dim intCounter As Integer
Using Option Explicit statement
It may be convenient to declare variables implicitly, but it can lead to errors
that may not be recognized at run time. Say, for example a variable by name intcount
is used implicitly and is assigned to a value. In the next step, this field is
incremented by 1 by the following statement
Intcount = Intcount + 1
This calculation will result in intcount yielding a value of 1 as
intcount would have been initialized to zero. This is because the intcount variable
has been mityped as incont in the right hand side of the second variable. But
Visual Basic does not see this as a mistake and considers it to be new variable
and therefore gives a wrong result.
In Visual Basic, to prevent errors of this nature, we can declare a variable
by adding the following statement to the general declaration section of the Form.
This forces the user to declare all the variables. The Option Explicit statement
checks in the module for usage of any undeclared variables and reports an error
to the user. The user can thus rectify the error on seeing this error message.
The Option Explicit statement can be explicitly placed in the general declaration
section of each module using the following steps.
- Click Options item in the Tools menu
- Click the Editor tab in the Options dialog box
- Check Require Variable Declaration option and then click the OK button
Scope of variables
A variable is scoped to a procedure-level (local) or module-level variable
depending on how it is declared. The scope of a variable, procedure or object
determines which part of the code in our application are aware of the variable's
existence. A variable is declared in general declaration section of e Form, and
hence is available to all the procedures. Local variables are recognized only
in the procedure in which they are declared. They can be declared with Dim
and Static keywords. If we want a variable to be available to all of
the procedures within the same module, or to all the procedures in an application,
a variable is declared with broader scope.
A local variable is one that is declared inside a procedure. This variable
is only available to the code inside the procedure and can be declared using the
Dim statements as given below.
Dim sum As Integer
The local variables exist as long as the procedure in which they are declared,
is executing. Once a procedure is executed, the values of its local variables
are lost and the memory used by these variables is freed and can be reclaimed.
Variables that are declared with keyword Dim exist only as long as the procedure
is being executed.
Static variables are not reinitialized each time Visual Invokes a procedure
and therefore retains or preserves value even when a procedure ends. In case we
need to keep track of the number of times a command button in an application is
clicked, a static counter variable has to be declared. These static variables
are also ideal for making controls alternately visible or invisible. A static
variable is declared as given below.
Static intPermanent As Integer
Variables have a lifetime in addition to scope. The values in a module-level
and public variables are preserved for the lifetime of an application whereas
local variables declared with Dim exist only while the procedure in which they
are declared is still being executed. The value of a local variable can be preserved
using the Static keyword. The follwoing procedure calculates the running total
by adding new values to the previous values stored in the static variable value.
Function RunningTotal ( )
Accumulate = Accumulate + num
RunningTotal = Accumulate
If the variable Accumulate was declared with Dim instead of static, the previously
accumulated values would not be preserved accross calls to the procedure, and
the procedure would return the same value with which it was called. To make all
variables in a procedure static, the Static keyword is placed at the beginning
of the procedure heading as given in the below statement.
Static Function RunningTotal ( )
The following is an example of an event procedure for a CommandButton that
counts and displays the number of clicks made.
Private Sub Command1_Click ( )
Static Counter As Integer
Counter = Counter + 1
The first time we click the CommandButton, the Counter starts with its default
value of zero. Visual Basic then adds 1 to it and prints the result.
Module Levele Variables
A module level variable is available to all the procedures in the module. They
are declared using the Public or the Private keyword. If you declare
a variable using a Private or a Dim statement in the declaration section of a
module—a standard BAS module, a form module, a class module, and so on—you're
creating a private module-level variable. Such variables are visible only from
within the module they belong to and can't be accessed from the outside. In general,
these variables are useful for sharing data among procedures in the same module:
' In the declarative section of any module
Private LoginTime As Date ' A private module-level variable
Dim LoginPassword As String ' Another private module-level variable
You can also use the Public attribute for module-level variables, for all module
types except BAS modules. (Public variables in BAS modules are global variables.)
In this case, you're creating a strange beast: a Public module-level variable
that can be accessed by all procedures in the module to share data and that also
can be accessed from outside the module. In this case, however, it's more appropriate
to describe such a variable as a property:
' In the declarative section of Form1 module
Public CustomerName As String ' A Public property
You can access a module property as a regular variable from inside the module
and as a custom property from the outside:
' From outside Form1 module...
Form1.CustomerName = "John Smith"
The lifetime of a module-level variable coincides with the lifetime of the
module itself. Private variables in standard BAS modules live for the entire life
of the application, even if they can be accessed only while Visual Basic is executing
code in that module. Variables in form and class modules exist only when that
module is loaded in memory. In other words, while a form is active (but not necessarily
visible to the user) all its variables take some memory, and this memory is released
only when the form is completely unloaded from memory. The next time the form
is re-created, Visual Basic reallocates memory for all variables and resets them
to their default values (0 for numeric values, "" for strings, Nothing
for object variables).
Public vs Local Variables
A variable can have the same name and different scope. For example, we can
have a public variable named R and within a procedure we can declare a local variable
R. References to the name R within the procedure would access the local variable
and references to R outside the procedure would access the public variable.