0

Win 7, Outlook 2013 I use VBA code that takes an action on some of the files that arrive in my inbox. However, I have to click/run button to run this macro.

Is there a way that this code could run automatically when an email arrives?

I have tried an Outlook rule to run the script but not successful.

I tried this, but this works only when once I run the macro

Private Sub Application_NewMail()
    Call GetAttachments_From_Inbox (My Macro)
End Sub
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
user2738649
  • 19
  • 1
  • 2
  • 5
  • 1
    I have created at least 10 projects in Outlook and in every project I have used Application_NewMail() without a problem. It works like a charm. The only problem with this function is that NewMail event will be called only for the mails received after you have opened your outlook. If your outlook is closed, and you received the mails in between, and then you start the Outlook again. The NewMail event will not be triggered for the mails which might have been received in the time the outlook was down. – Vikas Sep 04 '13 at 16:15

1 Answers1

0

I specifically use a script I run as a rule, applied to all messages. This gives you easy and clear access to the mail item you receive. Since you want to run this on each message setting up WithEvents on your inbox is probably your best bet.

For example:

You can create a listeners for an Outlook folder as follows:

Private WithEvents mainInboxItems As Outlook.Items

Public Sub Application_Startup()

    Dim olApp As Outlook.Application
    Dim objNS As Outlook.NameSpace
    Set olApp = Outlook.Application
    Set objNS = olApp.GetNamespace("MAPI")

    Set mainInboxItems = objNS.Folders("whatever your main mailbox is called").Folders("AssignNumber").Items
    'assumes your "AssignNumber" folder is a subfolder of the main inbox
    'otherwise you can nest Folders("myArchive").Folders("AssignNumber).items etc
End Sub

You can do this for as many folders as you want, too.

You can then assign the ItemAdd method to each of them like:

Private Sub mainInboxItems_ItemAdd(ByVal item As Object)
'do Stuff to mailitem
 Call GetAttachments_From_Inbox (item)
End Sub

All this code can go in ThisOutlookSession.

enderland
  • 13,825
  • 17
  • 98
  • 152
  • I have Inbox as my main mail box and once a particular file is found as attachment it downloads and moves to a folder 'Personal Mail' when i tried the above codes it gives error 'An object could not be found' Set mainInboxItems = objNS.Folders("whatever your main mailbox is called").Folders – user2738649 Sep 05 '13 at 06:46
  • @user2738649 you need to change "whatever your main inbox is called" to be the name of your inbox. Mine is something like, "Mailbox - enderland" – enderland Sep 05 '13 at 13:13
  • If it's being placed in `ThisOutlookSession` you don't need to name `Outlook.Application` : `Dim objNS AS NameSpace: Set objNS = GetNamespace("MAPI")` – Darren Bartrup-Cook May 25 '17 at 10:36