PDA

View Full Version : Get email from Outlook to Excel specified by received date



vitor
08-17-2018, 10:37 AM
Hi, Im trying to extract new emails from outlook to excel, but I am getting a error.


ub Test_Outlook2()

Dim OutlookApp As Outlook.Application
Dim OutlookNamespace As Namespace
Dim Folder As MAPIFolder
Dim OutlookMail As Variant
Dim i As Integer

Set OutlookApp = New Outlook.Application
Set OutlookNamespace = OutlookApp.GetNamespace("MAPI")
'Set Folder = OutlookNamespace.GetDefaultFolder(olFolderInbox).Folders("Net Sales Report").Folders("Sales")
Set Folder = OutlookNamespace.GetDefaultFolder(olFolderInbox)
i = 1


For Each OutlookMail In Folder.Items
If OutlookMail.ReceivedTime >= Range("From_date").Value Then
Range("eMail_subject").Offset(i, 0).Value = OutlookMail.Subject
Range("eMail_date").Offset(i, 0).Value = OutlookMail.ReceivedTime
Range("eMail_sender").Offset(i, 0).Value = OutlookMail.SenderName
Range("eMail_text").Offset(i, 0).Value = OutlookMail.Body

i = i + 1
End If
Next OutlookMail

Set Folder = Nothing
Set OutlookNamespace = Nothing
Set OutlookApp = Nothing

End Sub



after the line in red, shows the error: Run-time error '1004': Application-defined or object-defined error

freshpoet
08-17-2018, 01:14 PM
Hey,

you have to cast the date since it is a data type.

For Each OutlookMail In Folder.Items
If TypeName(OutlookMail) = "MailItem" Then
If CDate(OutlookMail.ReceivedTime) >= Range("Start_of_Month").value Then
If CDate(OutlookMail.ReceivedTime) <= Range("End_of_Month").value Then

vitor
08-21-2018, 08:06 AM
thank you very much. it worked