'Requires reference to Microsoft Outlook 11.0 Object Library
Option Explicit
Private Sub cmdImp_Click()
Dim startDate As Date, endDate As Date
Dim startRow As Long
If Not IsDate(DateBox1.Value) Then
MsgBox "Invalid Start Date: " & DateBox1.Value
DateBox1.Value = ""
DateBox1.SetFocus
Exit Sub
End If
If Not IsDate(DateBox2.Value) Then
MsgBox "Invalid End Date: " & DateBox2.Value
DateBox2.Value = ""
DateBox2.SetFocus
Exit Sub
End If
'Convert input dates to Date variables and repopulate textboxes to show user the actual dates being used.
'Include time in the end date to ensure emails received at any time on the end date are included
startDate = CDate(DateBox1.Value)
DateBox1.Value = Format(startDate, "dd/mm/yyyy")
endDate = CDate(DateBox2.Value & " 23:59:59 PM")
DateBox2.Value = Format(endDate, "dd/mm/yyyy")
Cells.ClearContents
startRow = 1
Import_Outlook_Emails startDate, endDate, startRow
MsgBox "Done"
End Sub
Private Sub Import_Outlook_Emails(startDate As Date, endDate As Date, row As Long)
Dim OutlookOpened As Boolean
Dim olApp As Outlook.Application
Dim olNS As Outlook.Namespace
Dim olFolder As Outlook.MAPIFolder
'Get or create Outlook application object and make sure it exists before continuing
On Error Resume Next
OutlookOpened = False
Set olApp = GetObject(, "Outlook.Application")
If Err.Number <> 0 Then
Set olApp = New Outlook.Application
OutlookOpened = True
End If
On Error GoTo 0
If olApp Is Nothing Then
MsgBox "Cannot start Outlook.", vbExclamation
Exit Sub
End If
Set olNS = olApp.GetNamespace("MAPI")
'Set olFolder = olNS.PickFolder
Set olFolder = olNS.Folders("Personal Folders").Folders("Inbox") 'MODIFY FOR REQUIRED FOLDER
Call ProcessFolder(olFolder, startDate, endDate, row)
If OutlookOpened Then
olApp.Quit
End If
End Sub
Private Sub ProcessFolder(olfdStart As Outlook.MAPIFolder, startDate As Date, endDate As Date, row As Long)
Dim olObject As Object
Dim olMail As Outlook.MailItem
For Each olObject In olfdStart.Items
If TypeName(olObject) = "MailItem" Then
Set olMail = olObject
If olMail.ReceivedTime >= startDate And olMail.ReceivedTime <= endDate Then
row = row + 1
Cells(row, 1) = olMail.Subject
If olMail.UnRead Then
Cells(row, 2) = "Message is unread"
Else
Cells(row, 2) = "Message is read"
End If
Cells(row, 3) = olMail.ReceivedTime
Cells(row, 4) = olMail.LastModificationTime
Cells(row, 5) = olMail.Categories
Cells(row, 6) = olMail.SenderName
Cells(row, 7) = olMail.FlagRequest
End If
End If
Next
End Sub