How to filter outlook emails for a specific date
I have the below macro which I use to download the email attachments from out with specific subject lines which are listed in an excel now i want to apply a filter on date .i.e. it should download the attachments from emails received on a specific date referred from a excel worksheet cell. I don't want to use a date range, I just want to define a specific date...
Code:
Sub Downloademailattachementsfromexcellist()
Dim olApp As Object
Dim olNS As Object
Dim olItem As Object
Dim olRecip As Object
Dim olShareInbox As Object
Dim lRow As Integer
Dim olAttach As Object
Dim strPath As String
Dim strName As String
Dim xlSheet As Worksheet
Dim iRow as Integer
Dim MailRcvdDate As Date
MailRcvdDate = Format(ThisWorkbook.Sheets("Email Download").Range("E2").Value, "mm/dd/yyyy")
Set olApp = OutlookApp("outlook.application")
Set olNS = olApp.GetNameSpace("MAPI")
'
Set olShareInbox = olNS.GetDefaultFolder(olFolderInbox).Folders(ThisWorkbook.Sheets("Email Download").Range("E2").Value)
Set xlSheet = ActiveWorkbook.Sheets("Email Download")
strPath = "C:\HP" & xlSheet.Range("C1").value & ""
If olShareInbox.Items.restrict("[UNREAD]=True").Count = 0 Then
MsgBox ("No Unread mails")
Else
CreateFolders strPath 'ensure the save path is present
For Each olItem In olShareInbox.Items.restrict("[UNREAD]=True")
lRow = xlSheet.Range("A" & xlSheet.Rows.Count).End(xlUp).Row ' + 1
lRow = xlSheet.Range("B" & xlSheet.Rows.Count).End(xlUp).Row
For Each olItem In olShareInbox.Items.restrict("[SentOn]= '"& MailRcvdDate &"' ")
For iRow = 1 To lRow 'declare the variable iRow as integer
'lRow = xlSheet.Range("A" & xlSheet.Rows.Count).End(xlUp).Row ' + 1
If InStr(1, olItem.Subject, xlSheet.Range("B" & iRow).value & "*") > 0 Then
If olItem.attachments.Count > 0 Then
For Each olAttach In olItem.attachments
strName = olAttach.FileName
olAttach.SaveAsFile strPath & strName
olItem.UnRead = False
Next olAttach
End If
Exit For 'subject found so stop looking
End If
Next iRow
Next olItem
End If
End Sub
Re: How to filter outlook emails for a specific date
Quote:
I don't want to use a date range, I just want to define a specific date...
you must use a date range for the day
>MailRcvdDate and < MailRcvdDate + 1
should cover all times during MailRcvdDate
formatting the value assigned to mailrcvddate is pointless as a date variable contains a number (double), not a string, even though it appears as a date, but you must format the date in the restrict query to us date format
an example from some code
Code:
Set nm = msgs.Restrict("[ReceivedTime] >= '" & Format(CDate(msg.ReceivedTime), "mm/dd/yyyy hh:nn") & "'")
this would work correctly for all dates from the date /time string from msg.receivedtime
and also
Code:
Set itms = itms.Restrict("[receivedtime] > '" & mydate & "' and [receivedtime] < '" & nxtday & "'")
in this case nxtday is mydate + 1 and as the both month and day of mydate are 1 (only the year changed) there was no need to format the date