Search code examples
vbaoutlookoutlook-2016

How to search by choosing a category from the category dialog?


I would like to search for keywords on the Outlook Search bar. The ideal process is that I can use search Tool hotkey to add the attributes (e.g. Sent To, Receiver, cc, etc.).

I intuitively think the attributes or keywords will exist on a specific mail item. It works when I search for Sent To, Receiver, and cc, but it has some problems when I would like to search a specific category by "Category". It will not show the complete Category List. There is a relevant comment here.

There is a relevant comment here

There is an illustrated picture for reference for the practical operation.

Illustrated picture for reference

Since I have lots of categories to manage my emails, I wish to choose a Category by Complete Category Dialog, and input it to Outlook Search Bar. Then I can more quickly and precisely find the mails I want.

There is my preliminary thinking for the VBA code. (Credit to MarcinSzaleniec):

Sub SearchByInputFromCategoryDialog
  'Open Category Dialog and choose one category
  StringOfCategory = Choosing Text
 
  txtSearch = "category:="category:(StringOfCategory )"
  myOlApp.ActiveExplorer.Search txtSearch, olSearchScopeAllFolders
end Sub

Then the category text would show onto Search Bar so that I can further keystroke the "enter" and start the searching process.

Remarks:

An issue might exist for Category Dialog, since I can't find if there exists the VBA approach to get the text of category by the category dialog.

The most information I found on the Internet mainly focus on an item or selected item on explorer to add the category by the category dialog, however the approach I would like to use is get category text by category dialog.


Solution

  • You can return the category from an object that supports categories.

    Option Explicit ' Consider this mandatory
    ' Tools | Options | Editor tab
    ' Require Variable Declaration
    ' If desperate declare as Variant
    
    Sub SearchByInputFromCategoryDialog()
    
        Dim StringOfCategory As String
        Dim txtSearch As String
        
        Dim obj As Object
            
        'Open Category Dialog and choose one category
        Set obj = CreateItem(olMailItem)
        obj.ShowCategoriesDialog
        StringOfCategory = obj.categories
        Debug.Print StringOfCategory
        
        'txtSearch = "category:=""Red category"""
        'Debug.Print txtSearch
        
        txtSearch = "category:=""" & StringOfCategory & """"
        Debug.Print txtSearch
         
        ActiveExplorer.Search txtSearch, olSearchScopeAllFolders
    
    End Sub