Reputation: 431
I'm wondering if there is a way to sort emails by date and then open the latest email found.
I'm trying to search for emails that has a unique tag inside the Body. In order to avoid duplicate emails that have the same tag, I have to sort these emails by date and open the latest email found so that I can reply to it.
Upvotes: 3
Views: 25384
Reputation: 49397
You need to Sort emails on the ReceivedTime property which returns a Date indicating the date and time at which the item was received.
Sub SortByDate()
Dim myNameSpace As Outlook.NameSpace
Dim myFolder As Outlook.Folder
Dim myItem As Outlook.MailItem
Dim myItems As Outlook.Items
Set myNameSpace = Application.GetNamespace("MAPI")
Set myFolder = myNameSpace.GetDefaultFolder(olFolderInbox)
Set myItems = myFolder.Items
myItems.Sort "[ReceivedTime]"
For Each myItem In myItems
MsgBox myItem.Subject & " ---- " & myItem.ReceivedTime
Next myItem
End Sub
Upvotes: 10
Reputation: 8591
For MS Outlook 2010 and higher use Items.Sort method.
Sub SortByDueDate()
Dim myNameSpace As Outlook.NameSpace
Dim myFolder As Outlook.Folder
Dim myItem As Outlook.TaskItem
Dim myItems As Outlook.Items
Set myNameSpace = Application.GetNamespace("MAPI")
Set myFolder = myNameSpace.GetDefaultFolder(olFolderTasks)
Set myItems = myFolder.Items
myItems.Sort "[DueDate]", False
For Each myItem In myItems
MsgBox myItem.Subject & "-- " & myItem.DueDate
Next myItem
End Sub
For previous versions, see this: Sorting Items in a Folder
Upvotes: 1