Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA Search in Outlook

Tags:

vba

outlook

I have this code to search in my folder. I do have a e-mail with the "sketch" subject, but VBA is not finding it (it goes to the ELSE clause)

Can anybody tell what is wrong ?

Set olApp = GetObject(, "Outlook.Application")

Set olNs = olApp.GetNamespace("MAPI")
Set olFldr = olNs.GetDefaultFolder(olFolderInbox)
Set olItms = olFldr.Items

Set Mail = olItms.Find("[Subject] = ""*sketch*""") 'Tracking
If Not (Mail Is Nothing) Then
    'use mail item here

Else
    NoResults.Show
End If
like image 899
AndroidDev Avatar asked Feb 04 '14 10:02

AndroidDev


1 Answers

Here is a way to do the search using Items Restrict.

This runs fast and you do not need to loop through the items to find the items that match the search criteria.

Sub Search_Inbox()

Dim myOlApp As New Outlook.Application
Dim objNamespace As Outlook.NameSpace
Dim objFolder As Outlook.MAPIFolder
Dim filteredItems As Outlook.Items
Dim itm As Object
Dim Found As Boolean
Dim strFilter As String


Set objNamespace = myOlApp.GetNamespace("MAPI")
Set objFolder = objNamespace.GetDefaultFolder(olFolderInbox)

strFilter = "@SQL=" & Chr(34) & "urn:schemas:httpmail:subject" & Chr(34) & " like '%sketch%'"

Set filteredItems = objFolder.Items.Restrict(strFilter)

If filteredItems.Count = 0 Then
    Debug.Print "No emails found"
    Found = False
Else
    Found = True
    ' this loop is optional, it displays the list of emails by subject.
    For Each itm In filteredItems
     Debug.Print itm.Subject
    Next
End If


'If the subject isn't found:
If Not Found Then
    'NoResults.Show
Else
   Debug.Print "Found " & filteredItems.Count & " items."

End If

'myOlApp.Quit
Set myOlApp = Nothing

End Sub
like image 144
jeffld Avatar answered Sep 28 '22 13:09

jeffld