You have probably heard some of these simple rules of life:
– If you open something, close it
– If you turn something on, turn it off
– If you spill something, wipe it up
These same rules apply to macro development. Many programmers get sloppy because they assume the computer will clean up for them. In most cases it does, but not always as soon as we would like. It is always good practice to clean up after yourself when exiting a routine or macro. This means closing any files you opened, unloading forms, etc.
Review the following function. You will see that the function level objects eEnum and eScan are set to Nothing prior to exiting.
Public Function ScanText() As Boolean
Dim eEnum As ElementEnumerator
Dim eScan As ElementScanCriteria
Set eScan = New ElementScanCriteria
Set eEnum = ActiveModelReference.Scan(eScan)
Do While eEnum.MoveNext
' do something with the text elements
Set eEnum = Nothing
Set eScan = Nothing
ScanText = True
For global (or Public) objects that are used by multiple routines you will need to construct an exit routine to be used as a common exit point for your macro. In the example below the ExitMacro routine unloads any forms and sets all public objects to Nothing.
Public gMyCollection As Collection
Public Sub MyMacro()
Set gMyCollection = New Collection
Public Sub ExitMacro()
Set gMyCollection = Nothing