VBA Search in Outlook
outlook, vba
Solution
The reason your `.Find` isn't working is because `Items.Find` doesn't support the use of wildcards. `Items.Find` also doesn't support searching partial strings. So to actually find the email, you'd need to remove the wildcards and include the entire string in your search criteria.
So here are your options:
If you know the full subject line you're looking for, modify your code like so:
Set Mail = olItms.Find("[Subject] = ""This Sketch Email""")
If you don't (or won't) know the full subject, you can loop through your inbox folder and search for a partial subject line like so:
Untested
Sub Search_Inbox()
Dim myOlApp As New Outlook.Application
Dim myNameSpace As Outlook.NameSpace
Dim myInbox As Outlook.MAPIFolder
Dim myitems As Outlook.Items
Dim myitem As Object
Dim Found As Boolean
Set myNameSpace = myOlApp.GetNamespace("MAPI")
Set myInbox = myNameSpace.GetDefaultFolder(olFolderInbox)
Set myitems = myInbox.Items
Found = False
For Each myitem In myitems
If myitem.Class = olMail Then
If InStr(1, myitem.Subject, "sketch") > 0 Then
Debug.Print "Found"
Found = True
End If
End If
Next myitem
'If the subject isn't found:
If Not Found Then
NoResults.Show
End If
myOlApp.Quit
Set myOlApp = Nothing
End Sub
Hope that helps!
Problem
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 ```