I use event handlers to automatically sort email in Outlook 2016. Those event handlers have been defined in ThisOutlookSession as Public WithEvents variables, they are set using the Application_Startup event, and they call different procedures located in a different code module which directly reference these event handler objects during the procedures.
This morning I get "object is required" error whenever these procedures are run. I turned on Option Explicit and it revealed that when I try to run the procedure manually I get a compile error indicating these variables (the public variable event handlers in ThisOutlookSession) are not defined. The error(s) stop when I either move the procedure to ThisOutlookSession or reference the event handler as "ThisOutlookSession.EventHandler1" instead of just "EventHandler1".
I could use these workarounds, but it would be a lot of work. Any idea what happened or how this could be fixed (without resorting to workarounds)?
Example code (in ThisOutlookSession):
Public WithEvents InboxItems As Outlook.Items
Public WithEvents InboxFolder As Outlook.Folder
Private Sub Application_Startup()
Initialize_handler
End Sub
Public Sub Initialize_handler()
Set InboxItems = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox).Items
Set InboxFolder = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
End Sub
Private Sub InboxItems_ItemAdd(ByVal oMail As Object)
Call Inbox_Sort
End Sub
Example code (in separate code module "Custom")
Sub Inbox_Sort()
Dim ML As Outlook.mailItem
Dim oObj As Object
For Each oObj In InboxItems
If TypeOf oObj Is mailItem Then
Call Sort(oObj)
Else
oObj.Move Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
End If
Next
End Sub