Title: Chapter 3 b Scope of Variables
1Chapter 3 bScope of Variables
3b
I
S
2
0
2
0
CI 9008 George Zolla
P
r
o
f
.
G
a
r
y
P
o
r
t
e
r
g
r
p
o
r
t
e
r
_at_
n
p
s
.
n
a
v
y
.
m
i
l
N
a
v
a
l
P
o
s
t
g
r
a
d
u
a
t
e
S
c
h
o
o
l
M
o
n
t
e
r
e
y
,
C
A
2Modules
- Modules - large units of code that comprise a
Visual Basic application - Code - the man behind the curtain
- Form Modules - contains a form and code for the
form - Standard Modules - contains code that is
typically used by other modules
3Procedures
- Procedures - smaller units that comprise a module
- Event procedure - automatically invoked by an
event - General procedure - explicitly invoked by another
procedure - Private procedure - accessible from within a
module - Public procedure - accessible from anywhere
4Variable Scope
- Variable Scope - The domain within which a
variable can be accessed. - Local Scope - Declared in private procedure.
- Module Scope - Use Dim statement placed in the
forms general declarations section. - Global Scope - Use Public statement in the
general declarations of a code module.
5Code Modules
- Identical to a form except there is no user
interface. - Code module contains only a general declarations
section. - It is a repository for data that must be shared
across forms.
6Declaring Local Variables
- Declare local variables using the Dim or Static
statements - Dim statement - value of variable preserved only
until procedure ends - Static statement - value of variable preserved
the entire time the local procedure is running
(Pg. 215)
7Lifetime of Variables
- Local Variables - Reset each time the event
procedure executes. - Module and Global Variables - Live as long as the
program executes. - button and button2 examples
8Local variables
l l l l l l l l
9Module-level variable
l l l l l l l l
10Module-level variable
l l l l l l l l
11Local variable hides module-level variable with
same name
12A globalvariable
l l l l
13The three levels of variable scope
l l l l
A local variable is declared in an event
procedure using a Dim statement. It can be
accessed only in the event procedure in which it
is declared.
14The three levels of variable scope
Form frmTestA
User interface
l l l l
A module-level variable is declared in the
general declarations section containing the Dim
statement. It can be accessed by any event
procedure on the same form as the general
declarations statement.
Code
15Project
Global Variables are declared in the general
declarations section of a code module using the
Public statement, and can be accessed by the code
in any event procedure anywhere in the project.
Code module modTest
User interface
Form frmTestA
Code
Code