Search notes:

VBA: lifetime of global variables

The following module and class is an attempt to get clarification about the lifetime of global variables.

tq84_obj.cls

This is a rather simple class with a constructor (class_initialize), a destructor (class_terminate), a member variable (name_) and a member function (sayHello) which basically says hello World, my name is … (and then appends the value of name_).
option explicit

public name_ as string

private sub class_initialize()
    debug.print"tq84_obj initialized"
end sub

private sub class_terminate()
    debug.print "tq84_obj finalized"
end sub

sub sayHello() ' {
    debug.print"Hello world, my name is " & name_
end sub ' }
Github repository about-VBA, path: /language/variables/global/lifetime/tq84_obj.cls

The module

The module declare two global variables, one is a simple double, the other the tq84_obj object.
option explicit

global g_obj as tq84_obj
global g_num as double

sub main() ' {
    set g_obj = new tq84_obj
    g_num     = 42
    g_obj.name_ = "main"
end sub ' }

sub finalize() ' {
    debug.print "finalize 1"
    end
    debug.print "finalize 2"
end sub ' }

function causeError(num as double) as double ' {
    causeError = 5 / num
end function ' }
Github repository about-VBA, path: /language/variables/global/lifetime/mod.bas

Test

The tests are conducted in the immediate window.

Initalizing the variables

First, the global variables are initialized by calling
main
Initizlizing g_obj implicititely calls the constructor of tq84_obj and consequently, the immediate window reports
tq84_obj initialized

Using the initalized variables

Next, I test if the global variables are available. Thus I execute the following two statements:
g_obj.sayHello()
? g_num
which prints
Hello world, my name is main
42
Thus, I see that the global variables were not destructed in the mean time.

Using end

The end (which is in the finalize sub) statement terminates all global variables:
finalize
The first debug.print statement in finalize prints
finalize 1
Because end terminates the execution of the currenlty running program, the second debug.print is not even executed.
Although the global variables were destroyed, the destructor of the object was not called. In order to verify their destruction, we need to again execute
g_obj.sayHello()
to which the runtime environment says Run-time error '91': Ojbect variable or With block variable not set.
And
? g_Num
prints
0

Causing an unhandled error

Global variables are also destroyed when an unhandled error occurs.
This is demonstrated similarly to the previous example:
main
causeError(0)
The runtime environment report Run-time error '11': Division by zero. I don't handle the error by just clicking the End buttun.
After that, the global variables are destroyed.

Index