Search code examples
vbaoutlookoutlook-filter

How to restrict items with multiple categories?


I've Access 2010 VBA code invoking Outlook to filter e-mail items.

The items must have two categories, e.g. "MOPS, PSA".

The way I use the keyword Restrict is as follows:

Set rootItems = oFolderRoot.Items
strCategory = sGroupCompanyName & ", MOPS"
'>>>
filterCriteria = "[Categories] = " & QuoteWrap(strCategory)
Set objItems = rootItems.Restrict(filterCriteria)

filterCriteria equals to [Categories] = 'PSA, MOPS'


Solution

  • When applying a filter using the Restrict method, the filter and property string must match exactly (up to case-sensitivity), for the filter to be applied.

    Since mail items may be assigned to multiple categories, you cannot rely on the order in which each category will appear in the comma-delimited string returned when accessing the Categories field programmatically.

    This is described in the MSDN documentation:

    Keywords (or Categories)

    The Categories field is of type keywords, which is designed to hold multiple values. When accessing it programmatically, the Categories field behaves like a Text field, and the string must match exactly.

    Values in the text string are separated by a comma and a space. This typically means that you cannot use the Find and Restrict methods on a keywords field if it contains more than one value.

    As such, your filter will need to account for both possible cases, using a filter string along the lines of:

    Set rootItems = oFolderRoot.Items
    Set objItems = rootItems.Restrict _
    ( _
        "[Categories] = '" & sGroupCompanyName & ", MOPS' OR " & _
        "[Categories] = 'MOPS, " & sGroupCompanyName & "'" _
    )