Home > Enterprise >  Outlook VBA Code stops firing after some time
Outlook VBA Code stops firing after some time

Time:02-23

The code below works perfectly:

Option Explicit

Dim myOlApp As New Outlook.Application

Public WithEvents myOlInspectors As Outlook.Inspectors

Private Sub Application_Startup()
    Initialize_handler
End Sub

Public Sub Initialize_handler()
    Set myOlInspectors = myOlApp.Inspectors
End Sub

Private Sub myOlInspectors_NewInspector(ByVal Inspector As Outlook.Inspector)
    Dim msg As Outlook.MailItem
If Inspector.CurrentItem.Class = olMail Then
    Set msg = Inspector.CurrentItem
    If msg.Size = 0 Then
        'MsgBox "New message"             ' TEST LINE
            msg.CC = "[email protected]"
    End If
End If
End Sub

However, after a few hours of works. It suddenly stops firing (and I don't get any error).

Is there something I missunderstand about the code?

Is there something about Outlook.Inspectors, that makes it stop launching for some reason?

CodePudding user response:

Your event method may fail if no item is currently open.

To add a CC recipient, you should do something like

Set myRecipient = msg.Recipients.Add("[email protected]") 
 
myRecipient.Type = olCC

Documentation

CodePudding user response:

Most probably the event is fired properly, but you have got an error in the code at runtime. The NewInspector event is not the best place for getting the CurrentItem property:

Private Sub myOlInspectors_NewInspector(ByVal Inspector As Outlook.Inspector)
    Dim msg As Outlook.MailItem
If Inspector.CurrentItem.Class = olMail Then
    Set msg = Inspector.CurrentItem
    If msg.Size = 0 Then
        'MsgBox "New message"             ' TEST LINE
            msg.CC = "[email protected]"
    End If
End If

Especially the following line of code could raise an error at runtime:

If Inspector.CurrentItem.Class = olMail Then

Instead, consider using the first Inspector`s Activate event which is fired when an inspector becomes the active window, either as a result of user action or through program code. So, in the first Activate event you could get item's properties without a problem.

Also you may consider adding On Error statement to the code so you could be aware why the event "is not fired".

  • Related