Module Level Variables

Often you want the variable to be available to other VBA procedures after the procedure in which the variable was declared has finished running. This situation requires that you change the scope of a variable. Instead of a procedure-level variable, you will want to declare a module-level variable.

Module-level variables are declared at the top of the module (above the first procedure definition) by using the Dim or Private statement. These variables are available to all of the procedures in the module in which they were declared, but are not available to procedures in other modules.

For instance, to make the slsTax variable available to any other procedure in the module, you could declare this variable by using the Dim or Private statement:

Option Explicit

Dim slsTax As Single ' module-level variable declared with Dim statement

Sub CalcCost()

...Instructions of the procedure... End Sub

Notice that the slsTax variable is declared at the top of the module, just below the Option Explicit statement (and before the first procedure definition). You could also declare the slsTax variable like this:

Option Explicit

Private slsTax As Single ' module-level variable declared with Private ' statement

Sub CalcCost()

...Instructions of the procedure... End Sub

^^ Note: There is no difference between module-level variables declared with

Dim or Private statements.

Before you can see how module-level variables actually work, you need another procedure that also uses the slsTax variable.

0 0

Post a comment