Consulting

Results 1 to 3 of 3

Thread: Open Email Message

  1. #1

    Open Email Message

    I would like to run some code whenever an email is double-clicked and opened. How do start this?

  2. #2
    Knowledge Base Approver
    The King of Overkill!
    VBAX Master
    Joined
    Jul 2004
    Location
    Rochester, NY
    Posts
    1,727
    Location
    Hi Stephanie,

    This is definately possible, though a little tricky in setting it up initially.

    Go to your outlook vba editor (Alt-F11 from outlook). Expand the ThisOutlookSession, and paste in the following:

    [vba]Option Explicit
    Dim myMailItemTrapper As MailEventClass
    Private Sub Application_Startup()
    Set myMailItemTrapper = New MailEventClass
    End Sub
    Private Sub Application_Quit()
    Set myMailItemTrapper = Nothing
    End Sub[/vba]Now, go to Insert, then Class Module. Single-click on the new class module in the project window, and press F4 to open the properties for it. Change the (Name) of the class module to "MailEventClass". Now, in the code pane for the class module, paste in the following:[vba]'Taken and modified from:
    'http://blogs.officezealot.com/legault/articles/2224.aspx
    Option Explicit
    Dim WithEvents objInspectors As Outlook.Inspectors
    Dim WithEvents objOpenInspector As Outlook.Inspector
    Dim WithEvents objMailItem As Outlook.MailItem
    Private Sub Class_Initialize()
    Set objInspectors = Application.Inspectors
    End Sub
    Private Sub Class_Terminate()
    Set objOpenInspector = Nothing
    Set objInspectors = Nothing
    Set objMailItem = Nothing
    End Sub
    Private Sub objInspectors_NewInspector(ByVal Inspector As Inspector)
    If Inspector.CurrentItem.Class = olMail Then
    Set objMailItem = Inspector.CurrentItem
    Set objOpenInspector = Inspector
    End If
    End Sub
    Private Sub objMailItem_Open(Cancel As Boolean)
    MsgBox "objMailItem_open has been triggered"
    End Sub

    Private Sub objMailItem_Read()
    MsgBox "objMailItem_Read has been triggered"
    End Sub[/vba]
    To start this, either just restart outlook, or press F5 in ThisOutlookSession when the cursor is in the application_startup event to manually run that.
    Any time you double-click a message, you'll see two message boxes telling you when the events are run (depending on when you want the code to be fired).
    When you make changes to the code, you'll have to re-run the application_startup event or restart outlook.

    Let us know if you have any questions!
    Matt

  3. #3
    That is awesome. Thank you so much for your help.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •