Modutete Vet Versus procedureteVet

Unlike data stored in Access tables, data stored in VBA variables (including arrays and constants) doesn't last too long. Each variable has a lifetime that defines how long it exists. Closely aligned with a variable's lifetime is its scope, which defines which objects in the database can and cannot access the variable. The scope and lifetime of a variable depend on where you define the variable within a module.

The top of a module, where you typically see Option Compare Database, is the declarations area. Here you can declare (sort of like announcing) settings, variables, constants, and arrays to all procedures in the module.

For example, the line Option Compare Database is a module-level declaration that announces to all procedures in the module that this code is running within the context of a database. When comparing values in code using logic like equals or greater than, the code should use the same rules as the rest of the database.

You can also declare and assign values to variables, arrays, and constants in the declarations area of the module. Those variables have module-level scope and lifetime. Thus, the variables are public in the sense that they are visible to all procedures and exist as long as any procedure in the module is running.

Variables, constants, and arrays declared inside a procedure have procedure-level lifetime and scope. Thus, they are private to the procedure. Each variable defined within a procedure is visible to only that procedure and exists only while that procedure is running.

The significance of module-level versus procedure-level becomes more apparent as you gain experience. For now, the main thing to keep in mind is that module-levels variables, constants, and arrays are declared at the top of a module, before the first procedure. Something that is procedure-level refers to variables, constants, and arrays defined within a procedure. Figure 4-4 illustrates the difference.

Figure 4-4:

Modulelevel and procedure-level declarations.

| VBA Practice - Module3 (Code)


-1 anyFunc

Option Compare Database

1 Module-level variables, constants, and arrays declared belotr. 'Their data is available to all procedures in this module. Const pi As Double = 3.141592 653 6 I

Dim length, width As Single Module-level Dim colors[5) As String -'

Sub anySub[)

'Variables, constants, arrays belotr are private to this procedure. Const c As Double = 34596000000# Dim energy, mass As Double

■ Procedure-level

'Any code can follow... End Sub

Function anyFunc [frmTJame As String) As Boolean

'Variables, constants, arrays below are private to this procedure. Dim answer As Boolean Dim scales[3) As Integer

'Any code can follow. End Function


0 0

Post a comment