Home > Enterprise >  How to automatically run a VBA macro (to do regex replacement of e-mail body text) when Outlook insp
How to automatically run a VBA macro (to do regex replacement of e-mail body text) when Outlook insp

Time:08-31

I have an Outlook VBA macro that does a regex replacement of some text in a reply/forward e-mail, using the WordMail representation of the e-mail.

I can trigger it from a button added to the ribbon. I want it to execute automatically immediately the inspector has opened, i.e. remove the need to remember to press the button once the editor is displayed. I have tried overloading the Open event, but the message does not appear to be accessible at that point - I think this gets invoked too early. None of the other events appears to be at the correct time.

Thank you for any suggestions.

CodePudding user response:

There are multiple events that you consider handling for such purposes.

The very first option is to handle the NewInspector event which is fired whenever a new inspector window is opened, either as a result of user action or through program code The inspector that was opened is passed as a parameter, so you can subscribe to the Activate event which is fired when an inspector becomes the active window, either as a result of user action or through program code. So, at this stage the item and the inspector window have been initialized and you are free to do any customizations.

You may find the Implement a wrapper for inspectors and track item-level events in each inspector article helpful.

The second option is to handle the MailItem.Reply event which is fired when the user selects the Reply action for an item, or when the Reply method is called for the item, which is an instance of the parent object.

CodePudding user response:

Inspectors.NewInspector event
Occurs whenever a new inspector window is opened, either as a result of user action or through program code

Option Explicit

' In ThisOutlookSession

Private WithEvents myOlInspectors As Inspectors

Private Sub Application_Startup_Temporary()
    Set myOlInspectors = Application.Inspectors
End Sub

Private Sub myOlInspectors_NewInspector(ByVal oInspector As Inspector)

    ' https://docs.microsoft.com/en-us/office/vba/api/outlook.inspectors.newinspector
    ' Occurs whenever a new inspector window is opened,
    '  either as a result of user action or through program code

    Dim msg As MailItem
    
    If oInspector.CurrentItem.Class = olMail Then
    
        Set msg = oInspector.CurrentItem
        
        If msg.Size > 0 Then
            Debug.Print "Subject: " & msg.subject
            Debug.Print " Non-zero size message opened."
            ' Your code here
        End If
        
    End If
    
End Sub

Private Sub myOlInspectors_NewInspector_Test()
    myOlInspectors_NewInspector ActiveInspector
End Sub
  • Related