Search code examples
vbaoutlookoutlook-2010

In VBA code for outlook rule, how to use/reference the email which caused the trigger


I have created a rule to run a script for when emails have certain headers. My script is trying to get the excel table content from the email and save that locally, to be further processed.

The below is a snippet I found and used: https://social.msdn.microsoft.com/Forums/en-US/22631e7e-53df-47c4-b625-22c9e935f02b/copy-a-table-from-body-of-an-email-to-excel-spreadsheet?forum=outlookdev

It works when I use Application.ActiveExplorer.Item, aka on the email that is open at the moment of running.

However, I wish to perform the below action on the email that triggered it. I tried to follow How to reference the mail which triggered the outlook macro? and their logic ByRef, but it did not work for me.

Can someone please advise on how I can get the table text by using GetInspector.WordEditor logic below on the trigger email? Thank you!

Sub getDailyCollMV(ByRef Item As Outlook.MailItem)
Dim r As Object  'As Word.Range
Dim doc As Object 'As Word.Document
Dim xlApp As Object, wkb As Object
Set xlApp = CreateObject("Excel.Application")
xlApp.DisplayAlerts = False
Set wkb = xlApp.Workbooks.Add
xlApp.Visible = False
xlApp.DisplayAlerts = False

Dim wks As Object
Set wks = wkb.Sheets(1)

For Each ItemVal In Application.ActiveExplorer.Item
Set doc = ItemVal.GetInspector.WordEditor
    For x = 1 To doc.tables.Count
     Set r = doc.tables(x)
        r.Range.Copy
       wks.Paste
       wks.Cells(wks.Rows.Count, 1).End(3).Offset(1).Select
    Next
Next

Solution

  • Replace the lines

    For Each ItemVal In Application.ActiveExplorer.Item
    Set doc = ItemVal.GetInspector.WordEditor
    

    with

    Set doc = Item.GetInspector.WordEditor