0

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
Community
  • 1
  • 1
BenN
  • 1
  • 1
  • The `Public` in `Public WithEvents InboxItems As Outlook.Items` should have no impact. This Excel reference https://bettersolutions.com/vba/events/withevents-keyword.htm is the most clear I found **"Can only be declared at the module level."**. Should apply to Outlook as well. Perhaps you had global variables, not related to WithEvents, you removed. – niton Aug 09 '20 at 23:41
  • If WithEvents variables are only ever able to be declared on a module level and referenced with respect to that module then you're right that I must've changed another global variable without realizing it. – BenN Aug 10 '20 at 16:54

0 Answers0