VBA Code to Read Outlook Emails

Outlook Tricks VBA

Reading emails from Outlook and capture them in Excel file is very common activity being performed in office environment. Doing this activity manually every time is quite boring and time consuming. Here is a VBA code that can help you in this, you can use this code to select an Outlook folder and read all emails from selected folder.

Excel Tricks

Public Sub ReadOutlookEmails()
    'Microsoft Outlook XX.X Object Library is required to run this code
    'Variable declaration
    Dim objFolder As Outlook.Folder
    Dim objNS As Outlook.Namespace
    Dim objMail As Outlook.MailItem
    Dim lCounter As Long
    'Set objects
    Set objNS = Outlook.GetNamespace("MAPI")
    Set objFolder = objNS.PickFolder
    'Validation if no folder picked by the user
    If TypeName(objFolder) = "Nothing" Then
        Exit Sub
    End If
    'Read emails from Outlook folder and update details in Sheet1
    For lCounter = 1 To objFolder.Items.Count
        Set objMail = objFolder.Items.Item(lCounter)
        Sheet1.Range("A" & lCounter + 5).Value = objMail.SenderName 'Sender name
        Sheet1.Range("B" & lCounter + 5).Value = objMail.To 'To
        Sheet1.Range("C" & lCounter + 5).Value = objMail.CC 'Cc
        Sheet1.Range("D" & lCounter + 5).Value = objMail.Subject 'Subject
        Sheet1.Range("E" & lCounter + 5).Value = objMail.ReceivedTime 'Email Received Time
        Sheet1.Range("F" & lCounter + 5).Value = objMail.Attachments.Count 'Attachment Count
    Next
    'Show confirmation message to user
    MsgBox "Done", vbInformation
End Sub

It is worth to mention that you must have MS Outlook installed in your system to use this code and you also need to add Office reference (Microsoft Outlook XX.X Object Library) in Excel VBA from Menu Bar (Tools>References…). Below are the steps to add Office reference in Excel VBA:

1. From the Menu Bar, click on Tools > References…

Excel Tricks

2. Select ‘Microsoft Outlook XX.X Object Library’ and click on ‘OK’ button

Excel Tricks

To use this code in your Excel file, follow below steps:

1. Open an Excel file
2. Press Alt+F11
3. Insert a Module (Insert>Module) from menu bar
4. Paste the code in the module
5. Now add a shape in Excel sheet
6. Give a name to the shape like ‘Read Outlook Emails’
7. Right click on the shape and select ‘Assign Macro…’

Excel Tricks

8. Select ‘ReadOutlookEmails’ from the list and click on ‘Ok’ button

Excel Tricks

9. Done

Outlook Email Management Tool

Leave a Reply

Your email address will not be published. Required fields are marked *