CST2601 Visual
Basic I
Notes on variable Scope
Understanding the Scope of VariablesThe scope of a variable defines which parts of your code are aware of its existence. When you declare a variable within a procedure, only code within that procedure can access or change the value of that variable; it has a scope that is local to that procedure. Sometimes, however, you need to use a variable with a broader scope, such as one whose value is available to all the procedures within the same module, or even to all the procedures in your entire application. Visual Basic allows you to specify the scope of a variable when you declare it. Scoping VariablesDepending on how it is declared, a variable is scoped as either a procedure-level (local) or module-level variable.
Variables Used Within a ProcedureProcedure-level variables are recognized only in the procedure in which they're declared. These are also known as local variables. You declare them with the Dim or Static keywords. For example:
–or–
Values in local variables declared with Static exist the entire time your application is running while variables declared with Dim exist only as long as the procedure is executing. Local variables are a good choice for any kind of temporary
calculation. For example, you can create a dozen different procedures
containing a variable called Variables Used Within a ModuleBy default, a module-level variable is available to all the procedures in that module, but not to code in other modules. You create module-level variables by declaring them with the Private keyword in the Declarations section at the top of the module. For example:
At the module level, there is no difference between Private and Dim, but Private is preferred because it readily contrasts with Public and makes your code easier to understand. Variables Used by All ModulesTo make a module-level variable available to other modules, use the Public keyword to declare the variable. The values in public variables are available to all procedures in your application. Like all module-level variables, public variables are declared in the Declarations section at the top of the module. For example:
Note You can't declare public variables within a procedure, only within the Declarations section of a module. For More Information For additional information about variables, see "Advanced Variable Topics." |