Reputation: 1
I use VBA to find email(s) by content of it's pdf attachment.
From what I understood, the only method without opening each email is Instant search.
I find the emails I look for. How do I work with emails that show as the result?
I didn't find how to save them to collection or something.
My search code:
Sub Search_Email()
Dim ol As Outlook.Application
Dim ns As Outlook.Namespace
Dim olFolder As Outlook.MAPIFolder
Dim strFilter, txtSearch As String
Set ol = New Outlook.Application
Set ns = ol.GetNamespace("MAPI")
Set olFolder = ns.Folders("RS Cash Application Inbox").Folders("Remittances")
Set ol.ActiveExplorer.CurrentFolder = olFolder
strFilter = "5860626494"
txtSearch = "attachment:" & strFilter
ol.ActiveExplorer.Search txtSearch, olSearchScopeCurrentFolder
End Sub
Result of the instant search. I need to download attachments from both displayed emails.
Upvotes: 0
Views: 829
Reputation: 49455
When calling Search
, the query is run in the user interface, and there is no programmatic mechanism to obtain the search results. Also the Search
method does not provide a callback to enable the developer to determine when the search is complete.
Instead, I'd suggest using the AdvancedSearch method of the Application
class which provides the callback to get the results after. The key benefits of using the AdvancedSearch method in Outlook are:
Restrict
and Find
/FindNext
methods can be applied to a particular Items
collection (see the Items
property of the Folder
class in Outlook).IsInstantSearchEnabled
property of the Store class).Stop
method of the Search class.To retrieve the search results you need to handle the AdvancedSearchComplete
event which is used to return the object that was created by the AdvancedSearch
method. This event only fires when the AdvancedSearch
method is executed programmatically.
Public blnSearchComp As Boolean
Private Sub Application_AdvancedSearchComplete(ByVal SearchObject As Search)
MsgBox "The AdvancedSearchComplete Event fired."
blnSearchComp = True
End Sub
Sub TestAdvancedSearchComplete()
Dim sch As Outlook.Search
Dim rsts As Outlook.Results
Dim i As Integer
blnSearchComp = False
Const strF As String = "urn:schemas:mailheader:subject = 'Test'"
Const strS As String = "Inbox"
Set sch = Application.AdvancedSearch(strS, strF)
While blnSearchComp = False
DoEvents
Wend
Set rsts = sch.Results
For i = 1 To rsts.Count
MsgBox rsts.Item(i).SenderName
Next
End Sub
After using the Search
on the Outlook UI you can get access to the CurrentView
by accessing corresponding properties on the Explorer
object. The View
class provides the Filter property which returns a string value that represents the filter for a view. The value of this property is a string, in DAV Searching and Locating (DASL) syntax, that represents the current filter for the view. So, you can use it for the AdvancedSearch
search string.
Upvotes: 1