Share via


Visual Basic Concepts

Releasing an ActiveX Component

When you are finished using an object, clear any variables that reference the object so the object can be released from memory. To clear an object variable, set it to Nothing. For example:

Dim acApp As Access.Application
Set acApp = New Access.Application
MsgBox acApp.SysCmd(acSysCmdAccessVer)
Set acApp = Nothing

All object variables are automatically cleared when they go out of scope. If you want the variable to retain its value across procedures, use a public or form-level variable, or create procedures that return the object. The following code shows how you would use a public variable:

Public wdApp as Word.Application
.
.
.
' Create a Word object and start Microsoft Word.
Set wdApp = New Word.Application
.
.
.
' Microsoft Word will not close until the
' application ends or the reference is set to Nothing:
Set wdApp = Nothing

Also, be careful to set all object references to Nothing when finished, even for dependent objects. For example:

Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Set xlApp = New Excel.Application
Set xlBook = xlApp.Workbooks.Add
Set xlApp = Nothing   ' Careful! xlBook may still
                     ' contain an object reference.
Set xlBook = Nothing   ' Now all the references
                     ' are cleared.