I am attempting to write a rule that applies a category to all incoming mail.
Ultimately I would like to use this to tag C and C++ related emails with a "Programming - C" and "Programming - C++" tags, but I simplified the example.
I also want to run this rule on mail that already has the specified categories, but I don't want it to double tag an email that is already tagged.
Here is the subroutine for adding a category without creating a duplicate:
' Add a category but don't create duplicates
Sub AddCategory(ByRef Item As MailItem, strCategory As String)
Dim exists As Boolean
Dim arrCategories As Variant
' Initialize variables
exists = False
arrCategories = Split(Item.categories, ",")
' Loop through all categories
For i = LBound(arrCategories) To UBound(arrCategories)
' Check if the specified category already exists
If StrComp(strCategory, arrCategories(i)) = 0 Then
exists = True
Exit For
End If
Next i
' If the category does not exist, add it
If Not exists Then
Item.categories = Item.categories & "," & strCategory
End If
End Sub
The subroutine that calls it:
Sub filter(Item As MailItem)
Call AddCategory(Item, "Programming - C")
Call AddCategory(Item, "Programming - C++")
Item.Save
End Sub
This filter subroutine is called from a rule and applies to all incoming mail.
If I run this rule on "All items in Inbox" and an email is already tagged with both "Programming -C" and "Programming - C++" it will duplicate the second tag.
So if "Programming - C" is the first tag it will duplicate "Programming - C++" and vice versa.
How can I check existing tags to avoid duplicates?
After figuring out how to use the VBA line by line debugger I eventually found the problem...
It turns out that Item.Categories
returns the categories as a string in the format:
"Category1, Category2, ..."
Each category is separated by a comma and a space.
The solution was to change the line:
arrCategories = Split(Item.categories, ",")
to
arrCategories = Split(Item.categories, ", ")