I want to search the email subject from the whole outlook (all folders and archive included). Do I change the getdefaultfolder or what should I do?
Sub SubjectFound()
Dim oOutlook As Object
Dim oInbox As Object
Dim oFilter As Object
Dim oNS As Object
Dim sFilter As String
Dim lr As Long, r As Long
Const olFolderInbox = 6
Set oOutlook = CreateObject("outlook.application")
Set oNS = oOutlook.GetNamespace("MAPI")
Set oInbox = oNS.getdefaultfolder(olFolderInbox)
lr = Range("A" & Rows.Count).End(xlUp).Row
For r = 2 To lr
sFilter = "@SQL=""urn:schemas:httpmail:subject"" = '" & Range("A" & r).Value & "'"
sFilter = sFilter & " AND "
sFilter = sFilter & "%today(""urn:schemas:httpmail:datereceived"")%"
Set oFilter = oInbox.items.restrict(sFilter)
Range("B" & r) = IIf(oFilter.Count > 0, "Task Completed", "Task Incomplete")
DoEvents
Next
Set oOutlook = Nothing
Set oNS = Nothing
Set oInbox = Nothing
Set oFilter = Nothing
End Sub
CodePudding user response:
Use Application.AdvancedSearch - it allows to search though multiple folders and their subfolders. Keep in mind that the search is asynchronous and you will need to wait until it finishes and/or use the Results object events.
CodePudding user response:
Use the AdvancedSearch
method of the Outlook Application
class which performs a search based on a specified DAV Searching and Locating (DASL) search string.
The key benefits of using the AdvancedSearch
method in Outlook are:
- The search is performed in another thread. You don’t need to run another thread manually since the
AdvancedSearch
method runs it automatically in the background. - Possibility to search for any item types: mail, appointment, calendar, notes etc. in any location, i.e. beyond the scope of a certain folder. The
Restrict
andFind
/FindNext
methods can be applied to a particularItems
collection (see theItems
property of theFolder
class in Outlook). - Full support for DASL queries (custom properties can be used for searching too). To improve the search performance, Instant Search keywords can be used if Instant Search is enabled for the store (see the
IsInstantSearchEnabled
property of theStore
class). - You can stop the search process at any moment using the
Stop
method of theSearch
class.
Read more about that method in the Advanced search in Outlook programmatically: C#, VB.NET article which I wrote for the technical blog and where you can find code sample and more detailed explanation of a possible use.