0

I am trying to write a brief VBA script that will move incoming messages from my Outlook Inbox to a subfolder. This is what I currently have (assembled from various posts), but I'm not getting any result when I send test emails. If there are any other posts that would relate to this, I would appreciate it!

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)

  On Error GoTo ErrorHandler
  Dim Msg As Outlook.MailItem
  Set myInbox = GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
  If TypeName(item) = "MailItem" Then
    Set Msg = item

    If Msg.SenderEmailAddress = "name@example.com" Then
        If InStr(0, Msg.Subject, "Subject Title", vbTextCompare) > 0 Then
        Msg.Move myInbox.Folders("Test").Subfolder("Destination")
        End If
    End If

  End If
ProgramExit:
  Exit Sub
ErrorHandler:
  MsgBox Err.Number & " - " & Err.Description
  Resume ProgramExit
End Sub
CJK
  • 99
  • 7
  • 20

2 Answers2

0

It looks like you didn't define and initialize the Items object properly. For example:

 Public WithEvents myOlItems As Outlook.Items

 Public Sub Initialize_handler()  
     Set myOlItems = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderContacts).Items  
 End Sub 

 Private Sub myOlItems_ItemAdd(ByVal Item As Object)  
    ' do something here
 End Sub

Be aware, the ItemAdd event is not fired when more than 16 items is added at the same time. This is a known issue in the OOM.

Try to use the NewMailEx event of the Application class instead. And I'd suggest reading the following series of articles:

Finally, is your macro enabled in Outlook? Have you checked out the Trust center settings?

Community
  • 1
  • 1
Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45
  • Well, I also updated the post. See the changes above. – Eugene Astafiev Jan 20 '15 at 19:14
  • Thank you for the suggestions! My macros are enabled, and I will experiment with the NewMailEx application. For the time being however, I'm still not getting any response from the current macro - I don't even get a notification when the test email comes through (i.e. no errors). Any ideas? – CJK Jan 20 '15 at 21:09
  • Did you check out the Trust center settings in Outlook? Is your macro allowed to run? – Eugene Astafiev Jan 21 '15 at 12:11
  • I changed the Macro Settings within the Trust Center to "Enable all macros". I believe this is the only relevant setting to running macros, correct? – CJK Jan 21 '15 at 14:17
0

Put your code in ThisOutlookSession.

Just above your code put

Public WithEvents Items As Items

When using the built-in class module ThisOutlookSession, Sub Application_Startup() initializes the handler.

niton
  • 8,771
  • 21
  • 32
  • 52