Blog

VBA code for Categories

Code which listens to Outlook events (ItemSend and Close) and checks if the item has a Category. If not it shows the Category assignment dialog.
Copy/paste from below:

'sources - https://ideasmiths.wordpress.com/2011/04/23/solution-to-create-vba-codes-for-outlook-inspector-close-event-handler/
'below http://www.vboffice.net/en/developers/assign-email-categories-before-sending/
'should be placed into ThisOutlookSession'

Option Explicit
'Creating Objects to listen for their events'
Public WithEvents myOlApp As Outlook.Application
Public WithEvents colInspectors As Outlook.Inspectors
Public WithEvents objInspector As Outlook.Inspector

'Call the subroutine to initialize the inspectors events on each Application Application_Startup
Private Sub Application_Startup()
    Init_agEventHandlers
End Sub

''
Private Sub Init_agEventHandlers()   
    Set myOlApp = Outlook.Application
    'Initialize the inspectors events handler
    Set colInspectors = Outlook.Inspectors
End Sub

Private Sub colInspectors_NewInspector(ByVal NewInspector As Inspector)
    'This is the code that creates a new inspector with events activated
    'Needed to handle cases when item was openned from explorer'
    Set objInspector = NewInspector
End Sub


'track send event to cover the outgoing(send) items - happens on Application level -> myOlApp
Private Sub myOlApp_ItemSend(ByVal Item As Object, Cancel As Boolean)
    On Error Resume Next
    If Len(Item.Categories) = 0 Then Item.ShowCategoriesDialog
    'and destroy the object to avoid the issue with event sequesnce (it's: Send -> Remove -> Close Inspector)
    Set objInspector = Nothing
End Sub


Private Sub objInspector_Close()
Dim myItem As Object
Set myItem = objInspector.CurrentItem
    If Len(myItem.Categories) = 0 Then myItem.ShowCategoriesDialog
End Sub