Search code examples
vbaoutlookoutlook-2010

Listeners on different mailboxes


I am looking to call a set of functions when I receive email to different mailboxes (if a mail arrives to [email protected] perform function1, if a mail arrives to [email protected] perform function2) I have the code below for one mailbox but I am unsure how to expand it to also listen on another mailbox without conflicting. How can I setup listeners for multiple mailboxes? Any help appreciated. Thank you

Private WithEvents Items As Outlook.Items

Private Sub Application_Startup()
   Dim olApp As Outlook.Application
   Dim objNS As Outlook.NameSpace
   Set olApp = Outlook.Application
   Set objNS = olApp.GetNamespace("MAPI")
   ' default local Inbox
   Set Items = objNS.GetDefaultFolder(olFolderInbox).Items
End Sub

Private Sub Items_ItemAdd(ByVal item As Object)
'do Stuff to mailitem
End Sub

Solution

  • Just add another WithEvent to watch the other folder:

    Private WithEvents Items As Outlook.Items
    Private WithEvents Items1 As Outlook.Items
    
    Private Sub Application_Startup()
       Dim olApp As Outlook.Application
       Dim objNS As Outlook.NameSpace
       Set olApp = Outlook.Application
       Set objNS = olApp.GetNamespace("MAPI")
       ' default local Inbox
       Set Items = objNS.GetDefaultFolder(olFolderInbox).Items
       Set Items1 = objNS.Folders.Item("[email protected]").Folders.Item("Inbox").Folders.Item("ASubFolder").Items
    End Sub
    
    Private Sub Items_ItemAdd(ByVal Item As Object)
    'do Stuff to mailitem
    End Sub
    
    Private Sub Items1_ItemAdd(ByVal Item As Object)
        'do stuff.
    End Sub