Tuesday, April 26, 2011

Variable Declaration - 3. Explicitly


There are many advantages to explicitly typing variables.  Primarily, we insure all computations are properly done, mistyped variable names are easily spotted, and Visual Basic will take care of insuring consistency in upper and lower case letters used in variable names.  Because of these advantages, and because it is good programming practice, we will explicitly type all variables.


To explicitly declare variables
Type
Option Explicit -  in the Declarations section of a class, form, or standard module:
–or–
From the Tools menu, choose Options, click the Editor tab and check the Require Variable Declaration option. This automatically inserts the Option Explicit statement in any new modules, but not in modules already created; therefore, you must manually add Option Explicit to any existing modules within a project.

   To explicitly type a variable, you must first determine its scope.  There are four levels of scope:

·          Procedure level
·          Procedure level, static
·          Form and module level
·          Global level

   Within a procedure, variables are declared using the Dim statement:

Dim MyInt as Integer
Dim MyDouble as Double
Dim MyString, YourString as String

Procedure level variables declared in this manner do not retain their value once a procedure terminates.

    To make a procedure level variable retain its value upon exiting the procedure, replace the Dim keyword with Static:

Static MyInt as Integer
Static MyDouble as Double

   Form (module) level variables retain their value and are available to all procedures within that form (module).  Form (module) level variables are declared in the declarations part of the general object in the form's (module's) code window.  The Dim keyword is used:

Dim MyInt as Integer
Dim MyDate as Date

   Global level variables retain their value and are available to all procedures within an application.  Module level variables are declared in the declarations part of the general object of a module's code window.  (It is advisable to keep all global variables in one module.)  Use the Global keyword:

Global MyInt as Integer
Global MyDate as Date

·         What happens if you declare a variable with the same name in two or more places?  More local variables shadow (are accessed in preference to) less local variables.  For example, if a variable MyInt is defined as Global in a module and declared local in a routine MyRoutine, while in MyRoutine, the local value of MyInt is accessed.  Outside MyRoutine, the global value of MyInt is accessed.


No comments:

Post a Comment