2.3. Ending Your VB Program

At some stage, most users want to exit from a program. OK, yours might be a really great program, but unfortunately the user may want to go off and do something else—like go home! You have to allow your application to both exit and tidy up before it ends. One advantage you have when building an application in a VBA-hosted environment is that you don't have to worry too much about finishing the program; the majority of the work is taken care of by the host application. You just have to ensure that any object references are cleaned up, and all database connections closed. You can place this type of code in the Close event. VB developers writing executables have to take care of unloading the application themselves, but in most cases this is no more onerous a task than in VBA; this section shows you how.

2.3.1. How to End Your Program

If you specified a form as the startup object, then you must unload this form to close the application. You can do this by including the following statement somewhere in the form, usually in the event handler of an Exit menu option or Exit command button:

Unload Me

If you specified a Sub Main procedure as the startup object, the program terminates when the Sub Main procedure is completed. For example, here's the Sub Main you saw earlier in this chapter:

Sub Main()
    Dim oForm as frmStartUp
    Set oForm = New frmStartUp
        oForm.Show vbModal
    Set oForm = Nothing
End Sub

Because the form is shown modally, the Sub Main procedure doesn't ...

Get VB & VBA in a Nutshell: The Language now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.