How to create an Outlook search folder using VBA

Last reviewed on August 7, 2014   —  9 comments

One thing that really annoys me about Outlook is that I can right click on a message and do pretty much anything I might want to do, except create a search folder.

I like to create search folders for people who hire me then when the project is finished, I delete the search folder.

Find Related is slow and not persistent. Plus, looking over the list of search folders helps me remember who I'm looking for. :)

Use VBA to create an Instant search for messagesfrom the selected contact.

VBA to the rescue (as always!) The following code creates a search folder using either the sender's display name or email address. It's an amazingly fast search. Next on my to-do list: use VBA to replace the Activities tab.

Error # -2147219964 : Cannot create folder. is trying to tell you that the folder name exists. Use the DeleteSearchFolder macro to delete it, then recreate it.

Create search folder for message sender macro

Open the VBA editor using Alt+F11, paste the code into the editor. Select a message and run the macro.

The current iteration works only on the default Inbox (and subfolders). It can easily be tweaked to use a selected contact:
Dim oMail As Outlook.ContactItem
strFilter = oMail.Email1Address

Sub SearchFolderForSender()
On Error GoTo Err_SearchFolderForSender

Dim strFilter As String

' lets get the email address from a selected message
Dim oMail As Outlook.MailItem
Set oMail = ActiveExplorer.Selection.Item(1)
strFilter = oMail.SenderEmailAddress

If strFilter = "" Then Exit Sub

Dim strDASLFilter As String

' From email address
Const From1 As String = ""
Const From2 As String = ""
strDASLFilter = "(""" & From1 & """ CI_STARTSWITH '" & strFilter & "' OR """ & From2 & """ CI_STARTSWITH '" & strFilter & "')"

' From Display name
'strDASLFilter = """urn:schemas:httpmail:fromname"" LIKE '" & strFilter & "' "

Dim strScope As String
strScope = "Inbox"

Dim objSearch As Search
Set objSearch = Application.AdvancedSearch(Scope:=strScope, Filter:=strDASLFilter, SearchSubFolders:=True, Tag:="SearchFolder")

'Save the search results to a searchfolder
objSearch.Save (strFilter)

Set objSearch = Nothing

Exit Sub

MsgBox "Error # " & Err & " : " & Error(Err)

End Sub

Delete the Search folder

To delete the search folder you created using the code above, you can use a macro such as this one.

This is a tweaked version of the macro at (Less Than) Portable Search Folders. I tweaked it to look for a search folder that uses the sender's address (oMail.SenderEmailAddress) from a selected message.

Sub DeleteSearchFolder()

    Dim CommonViewsEIDBin As String
    Dim CommonViewsEIDString As String
    Dim CommonViewsFolder As Folder
    Dim ACTable As Table
    Dim oRow As Row
    Dim SFDefinitionEID As String
    Dim SFDefinitionItem As StorageItem

Dim strFilter As String
Dim oMail As Outlook.MailItem
Set oMail = ActiveExplorer.Selection.Item(1)
strFilter = oMail.SenderEmailAddress

CommonViewsEID = Session.DefaultStore.PropertyAccessor.GetProperty("")
    CommonViewsEIDString = Session.DefaultStore.PropertyAccessor.BinaryToString(CommonViewsEID)
    Set CommonViewsFolder = Session.GetFolderFromID(CommonViewsEIDString)
    Set ACTable = CommonViewsFolder.GetTable("[Subject] = '" & strFilter & "'", olHiddenItems)
    Set oRow = ACTable.GetNextRow()
    If (Not (oRow Is Nothing)) Then
        SFDefinitionEID = oRow("EntryID")
        Set SFDefinitionItem = Session.GetItemFromID(SFDefinitionEID)
    End If

End Sub

Searching other fields

You can search any Outlook field if you know the field name and filter code to use. The easiest way to find out what you need to replicate a filter is to create a filter in Outlook then check the SQL tab.

You can use the httpmail and mailheader namespace schemas for some fields, but some search queries, such as the sender's actual email address, need the mapi property tag.

The httpmail and mailheader schemas are listed on the following pages at MSDN: urn:schemas:httpmail: Namespace and urn:schemas:mailheader: Namespace.

To pick up a value from a different Outlook field, change the field name in
strFilter = oMail.SenderEmailAddress and change the search string used in strDASLFilter

This long filter covers the common search fields.

strDASLFilter = """urn:schemas:httpmail:fromname"" LIKE '%" & strFilter & "%' " + _ 
"OR ""urn:schemas:httpmail:textdescription"" LIKE '%" & strFilter & "%' " + _ 
"OR ""urn:schemas:httpmail:displaycc"" LIKE '%" & strFilter & "%' " +  _ 
"OR ""urn:schemas:httpmail:displayto"" LIKE '%" & strFilter & "%' " +  _ 
"OR ""urn:schemas:httpmail:subject"" LIKE '%" & strFilter & "%' " +  _ 
"OR ""urn:schemas:httpmail:thread-topic"" LIKE '%" & strFilter & "%' " +  _ 
"OR """" LIKE '%" & strFilter & "%' " +  _ 
"OR ""{00062008-0000-0000-C000-000000000046}/8586001f"" LIKE '%" & strFilter & "%' " +  _ 
"OR ""{00062008-0000-0000-C000-000000000046}/85a4001f"" LIKE '%" & strFilter & "%' " +  _ 
"OR ""{00062041-0000-0000-C000-000000000046}/8904001f"" LIKE '%" & strFilter & "%' " + "OR """" LIKE '%" & strFilter & "%' " +  _ 
"OR """" LIKE '%" & strFilter & "%' " +  _ 
"OR """" LIKE '%" & strFilter & "%' " + "OR """" LIKE '%" & strFilter & "%' " +  _ 
"OR """" LIKE '%" & strFilter & "%' "

Written by

Diane Poremsky
A Microsoft Outlook Most Valuable Professional (MVP) since 1999, Diane is the author of several books, including Outlook 2013 Absolute Beginners Book. She also created video training CDs and online training classes for Microsoft Outlook. You can find her helping people online in Outlook Forums as well as in the Microsoft Answers and TechNet forums.

Please post long or more complicated questions at Outlookforums.

9 responses to “Use VBA to create an Outlook search folder using the selected message”

  1. Evan

    Could you please rewrite the script to create a search folder based on selected item's categories?

  2. Larry in AZ

    Hello Diane.

    I am using the code that you posted above. Thanks for the information. It has caused me to try to expand upon it, but I am having troubles trying to make my ideas work.

    I am trying to create a Search Folder where any of the following are true:

    1) keyword matches found in my "Inbox" by "from", "subject" or found in the message body
    2) keyword matches found in my "Sent Items" by "to", "subject" or found in the message body
    3) keyword matches found in my archived rec'd messages by "from", "subject" or found in the message body
    4) keyword matches found in my archived sent messages by "to", "subject" or found in the message body

    I guess my trouble is building the query.

    Any assistance that you (or anyone else) can provide would be greatly appreciated!

    Thanks in advance.

  3. Andreas

    I'm using Outlook 2013 ann VB for applications 7.1

    the script works fine but if I change the DASL Filter to the SQL Output of query builder I don't get it to work at all

    VBA does not accept the Syntax of the query builder SQL window

    I would like to have a query like this:

    ("urn:schemas:httpmail:fromname" LIKE '%sender1%' OR ("urn:schemas:httpmail:displayto" LIKE '%sender1%' AND "urn:schemas:httpmail:fromname" LIKE '%sender2%') OR ("urn:schemas:httpmail:displaycc" LIKE '%sender1%' AND "urn:schemas:httpmail:fromname" LIKE '%sender2%'))

    Sender1 is the Person I want to check for
    Sender2 is fix (me)

    overall the script should emulate something like the All by Person from Notes.

    any help or hint is highly welcome

    Kind regards

Leave a Reply

If the Post Coment button disappears, press your Tab key.