问题
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
回答1:
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.
来源:https://stackoverflow.com/questions/18602116/trigger-vba-code-to-run-after-a-new-mail-is-received-in-outlook