Another common use of the Forms Collection
is to unload all forms. Although the End statement
would provide a faster, simpler way to terminate
the application, it can have unwanted effects
because a call to End will immediately terminate
the application without allowing any further
events (such as Unload events) to run. Looping
through the Forms Collection to unload all members
might seem like a more complicated way to do
the task, but it allows normal processing of
Unload and other events.
The code of Listing 4.18 shows one way to
control the loop. First, you must determine
the total number of elements in the collection
then reduce that number by one to accommodate
for that fact that the collection is 0-based.
The loop unloads collection members in reverse
order from the highest-numbered member to the
lowest. This is due to the fact that, after
each unload of a collection member, the number
of members in the collection decreases by one.
UNLOADING ALL FORMS WITH A DESCENDING FOR...NEXT LOOP
Dim iLoop As Integer
Dim iHighestForm as integer
iHighestForm = Forms.Count — 1
For iLoop = iHighestForm To 0 Step — 1
A more elegant way to unload all forms would
be with a For...Each loop, as in the example
of Listing 4.19.
UNLOADING ALL FORMS WITH A FOR...EACH LOOP
Dim frmCurr as Form
For each frmCurr in Forms
Both of the above methods assume that at least one form has been loaded in
the collection and that a command button named cmdClose is on one of the loaded
forms. After run, all forms should be unloaded, and the project will terminate
if no other forms are in memory.
Using the forms collection topics