I am creating a macro to get email by subject and received date in our team shared box. My problem is that once I select date (e,g 1/16/2018 to 1/17/2018), only few emails are stored in object. In below screenshot, I have 9 items which are applied restrict method. It should be 14 items emails which are received after 1/16/2018 to now(right outlook mail in screenshot), but 5 emails are not stored in object. can anyone help me out? I'm STUCK!
Sub GetFromOutlook()
Dim OutlookApp As Outlook.Application
Dim OutlookNamespace As Namespace
Dim Folder As MAPIFolder
Dim OutlookMail As Variant
Dim i As Integer
Dim olItems As Outlook.Items
Dim myItems As Outlook.Items
Dim DateStr As Date
Dim DateEnd As Date
Dim oOlResults As Object
Dim DateToCheck As String
Dim DateToCheck2 As String
Dim DateToCheck3 As String
Set OutlookApp = New Outlook.Application
Set OutlookNamespace = OutlookApp.GetNamespace("MAPI")
Dim olShareName As Outlook.Recipient
Set olShareName = OutlookNamespace.CreateRecipient("[email protected]")
Set Folder = OutlookNamespace.GetSharedDefaultFolder(olShareName, olFolderInbox).Folders("sub1").Folders("sub2")
Set olItems = Folder.Items
'DateStr = 1/16/2018
'DateEnd = 1/17/2018
DateStr = Format(Range("From_Date").Value, "DDDDD HH:NN")
DateEnd = Format(Range("To_Date").Value, "DDDDD HH:NN")
'DateStr = DateAdd("d", -1, DateStr)
'DateEnd = DateAdd("d", 1, DateEnd)
DateToCheck = "[ReceivedTime] > """ & DateStr & """"
DateToCheck2 = "[ReceivedTime] <= """ & DateEnd & """"
DateToCheck3 = "[SenderName] = ""[email protected]"""
Set myItems = olItems.Restrict(DateToCheck)
Set myItems = myItems.Restrict(DateToCheck2)
Set myItems = myItems.Restrict(DateToCheck3)
i = 1
For Each myitem In myItems
' MsgBox myitem.ReceivedTime
Range("eMail_subject").Offset(i, 0).Value = myitem.Subject
Range("eMail_date").Offset(i, 0).Value = myitem.ReceivedTime
i = i + 1
Next myitem
Set Folder = Nothing
Set OutlookNamespace = Nothing
Set OutlookApp = Nothing
End Sub
See Question&Answers more detail:os