IE 212: COMPUTATIONAL METHODS FOR INDUSTRIAL ENGINEERING
EXAMPLE FOR LECTURE NOTES #4
VARIABLE SCOPE
INSTRUCTIONS
1. Start by inserting two modules to the project explorer.
2. Create two sub procedures in each module
a) Mod1_Proc1
b) Mod1_Proc2
c) Mod2_Proc1
d) Mod2_Proc2
3. Add the following variable declarations at the top of Module1:
a) Dim mod1PrivateVar As String (can use keyword Private too)
b) Private Const pi As Double = 3.1416 (cannot use keyword Dim)
Run all sub procedures in both modules to illustrate that, with the current variable scope, the two
variables can only be "seen" in Module1. The sub procedures in Module2 will report an error
when they are executed. Also point out that Excel VBA will not allow a programmer to assign a
value to a variable with a Private scope at the module level this must be done inside each sub
procedure. However, Excel VBA expects that a value will be assigned to a constant, regardless of
whether it is declared with a Public or Private scope.
4. Change the variable declarations at the top of Module1 as follows:
a) Public mod1PrivateVar As String
b) Public Const pi As Double = 3.1416
Run all sub procedures in both modules to illustrate that, with the new variable scope, the two
variables can be "seen" in both Module1 and Module2.
MODULE1 CODE MODULE2 CODE
Option Explicit Option Explicit
Public mod1PrivateVar As String Sub Mod2_Proc1()
Public Const pi As Double = 3.1416 Dim refCell As Range
Set refCell = Range("D2")
Sub Mod1_Proc1()
Dim refCell As Range With refCell
Set refCell = Range("B2") .Offset(0, 0).Value =
mod1PrivateVar
mod1PrivateVar = "Var_Sub1" .Offset(1, 0).Value = pi
With refCell End With
.Offset(0, 0).Value = End Sub
mod1PrivateVar
.Offset(1, 0).Value = pi Sub Mod2_Proc2()
End With Dim refCell As Range
End Sub Set refCell = Range("D5")
Sub Mod1_Proc2() With refCell
Dim refCell As Range .Offset(0, 0).Value =
Set refCell = Range("B5") mod1PrivateVar
.Offset(1, 0).Value = pi
mod1PrivateVar = "Var_Sub2" End With
With refCell End Sub
.Offset(0, 0).Value =
mod1PrivateVar 1
.Offset(1, 0).Value = pi
End With
End Sub