Monday, September 20, 2021

Find mail by date time,unread status or importance(high normal or low) in outlook using vba

Sub findemail()
Dim olApp, olAccts, olInspect, filteredList As Object
Set olApp = CreateObject("Outlook.Application")
Dim olFolder As Outlook.MAPIFolder
Dim count As Integer
Dim xDate As Date

'get yesterday date
xDate = Date - 2
'MsgBox (xDate)
count = 0
Set olFolder = olApp.GetNamespace("MAPI").Folders("allsourav@gmail.com")
'If (olFolder.Folders.count > 0) Then
'    For Each Folder In olFolder.Folders
'        MsgBox (Folder.Name)
'
'    Next
'End If
Set olFolder = olApp.GetNamespace("MAPI").Folders("allsourav@gmail.com").Folders("[Gmail]")
If (olFolder.Folders.count > 0) Then
    For Each Folder In olFolder.Folders
        MsgBox (Folder.Name)
        
    Next
End If
Set olFolder = olFolder.Folders("Sent Mail")

Dim itmemail As Outlook.MailItem
Set filteredList = olFolder.Items
'numeral
'Set itmemail = filteredList.Find("[Importance]=2") 'mail with high importance
'we can use a variable like this
'strFind = "[Importance]=2"

'boolean
'strFind = "[UnRead]=False"

'search by date and time
strFind = "[ReceivedTime] >= '" & CStr(xDate - 10) & " 12:00AM' AND [ReceivedTime] < '" & CStr(xDate - 1) & " 12:00AM'"

MsgBox (strFind)


Set itmemail = filteredList.Find(strFind)
While Not itmemail Is Nothing

Debug.Print itmemail.Subject, itmemail.SenderName, itmemail.ReceivedTime
Debug.Print itmemail.Body
On Error Resume Next
Set itmemail = filteredList.FindNext


Wend


End Sub

No comments:

Post a Comment