Trigger VBA code to run after a new mail is received in Outlook? [duplicate]

﹥>﹥吖頭↗ 提交于 2019-12-23 05:12:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!