3.7. Variable Scope and Lifetime

Sometimes you need a variable to be seen by all the procedures within your project, while other variables should only be available within a particular procedure. The visibility of a variable is known as its scope. Closely related to a variable's scope is its lifetime, or the period of program execution when the variable is live and available for use. Precisely where you declare a variable or constant in a program determines its scope and its lifetime.

In a nutshell, variables declared in the declarations section of a module using the Private keyword can be accessed by all the procedures within the module. Variables declared in the declaration section of a code module using the Public keyword can be accessed by the whole project. Variables declared in the declaration section of a class module using the Public keyword can be accessed by the whole project once an object reference has been made to the class. And variables declared using the Dim statement within a subroutine or function can only be accessed in the procedure in which they've been declared.

3.7.1. Procedure-Level Scope

A variable that is declared within an individual procedure (that is, within a subroutine or a function) can only be used within that procedure, and is therefore said to have procedure-level scope. You can therefore define different variables that use the same name in different procedures (like the simple x variable commonly used in the For...Next loop). You can even ...

Get VB & VBA in a Nutshell: The Language now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.