Link to home
Start Free TrialLog in
Avatar of stopher2475
stopher2475Flag for United States of America

asked on

Get Email Fields in VBA

I want to write a VBA macro to get the field values (subject, body, To, etc) from an email. I will run it from a toolbar.
I know how to create an email and edit them there but how do I get them from an already created email that is open or currently selected?
Avatar of stopher2475
stopher2475
Flag of United States of America image

ASKER

I found some code to get the currently selected email.
The one problem with it is that if I have another email open that is not the
one selected in the explorer window the user might be getting data from the wrong email.
Is there any way to use the current email if thats where you're running it from?

Public Sub GetMailFields()
Dim objExplorer As Outlook.Explorer
Dim objSelection As Outlook.Selection
Dim objItem As Outlook.MailItem 'Object
Dim strheader As String

' MAPI property tag used
objSession.Logon , , False, False, 0 ' Use the existing Outlook session

Set objExplorer = ThisOutlookSession.ActiveExplorer
Set objSelection = objExplorer.Selection

' Get selected Message ID
Set objItem = objSelection.Item(1)

MsgBox objItem.Subject & Chr(10) & _
        objItem.To & Chr(10) & _
        objItem.SentOn

' Tidy up
Set objExplorer = Nothing
Set objSelection = Nothing
Set objItem = Nothing

End Sub
Found out how to get the currently open email as well.
Added a condition to use ThisOutlookSession.ActiveInspector.CurrentItem
if the active window wasn't the activeexplorer.

Public Sub GetMailFields()
   
    Dim objExplorer As Outlook.Explorer
    Dim objSelection As Outlook.Selection
    Dim objItem As Outlook.MailItem 'Object
    Dim strheader As String
   
    ' MAPI property tag used
    'objSession.Logon , , False, False, 0 ' Use the existing Outlook session
   
    Set objExplorer = ThisOutlookSession.ActiveExplorer
    Set objSelection = objExplorer.Selection
   
    ' Get selected Message ID
    If ThisOutlookSession.ActiveWindow = objExplorer Then
        Set objItem = objSelection.Item(1)
    Else
        Set objItem = ThisOutlookSession.ActiveInspector.CurrentItem
    End If
   
    MsgBox objItem.Subject & Chr(10) & _
            objItem.To & Chr(10) & _
            objItem.SentOn
   
   
    ' Tidy up
    Set objExplorer = Nothing
    Set objSelection = Nothing
    Set objItem = Nothing

End Sub
ASKER CERTIFIED SOLUTION
Avatar of David Lee
David Lee
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial