Home > database >  Why doesn't the "Quit" event in Outlook VBA run a passed class module?
Why doesn't the "Quit" event in Outlook VBA run a passed class module?

Time:05-20

I have a macro that, upon the closing of the Outlook client, a private variable is set to an instance of a class module. The code runs fine and no errors are thrown. However, the class module that is passed (please correct me if I am using the wrong terminology), does not have its subroutine run.

The goal is to create and save a new note item upon application exit.

From "ThisOutlookSession" (Microsoft Outlook Object):

Option Explicit

Private ShutdownTrigger As Class2

Private Sub Application_Quit()
      
    Set ShutdownTrigger = New Class2
    
End Sub

From "Class2" (Class Module):

Option Explicit

 Private Sub ExitApp()
 
    Dim olApp As Outlook.Application
    Dim olNS As Outlook.NameSpace
    Dim olNoteItm As Outlook.NoteItem

    Set olApp = Outlook.Application
    Set olNS = olApp.GetNamespace("MAPI")
    
    Set olNoteItm = olApp.CreateItem(olNoteItem)
    
    With olNoteItm
    
    .Body = "murphy"
    
    End With
    
    olNoteItm.Save

 End Sub

Currently, the new note is not being created. Note, the subroutine "ExitApp" code works when placed within the "ThisOutlookSession" object, however.

Also, as an potentially unrelated question, do I need to create a private variable "Shutdown Trigger", or can I use a Dim statement as I do in most subroutines?

Thanks for the help!

CodePudding user response:

First of all, there is no need to create a new Outlook Application instance in the code to create a new note item Outlook. Instead, you could get an Application instance in the ThisOutlookSession module and pass it to the method.

Second, you need to call the ExitApp method on the object created:

Option Explicit

Private ShutdownTrigger As Class2

Private Sub Application_Quit()
      
    Set ShutdownTrigger = New Class2
    ShutdownTrigger.ExitApp()
    
End Sub

Third, the method may look in the following way:

Option Explicit

 Private Sub ExitApp(olApp As Outlook.Application)
    Dim olNS As Outlook.NameSpace
    Dim olNoteItm As Outlook.NoteItem

    Set olNS = olApp.GetNamespace("MAPI")
    
    Set olNoteItm = olApp.CreateItem(olNoteItem)
    
    With olNoteItm
    
    .Body = "murphy"
    
    End With
    
    olNoteItm.Save

 End Sub

Read more about class modules in VBA in the VBA Class Modules – The Ultimate Guide article.

  • Related