在 Outlook 中收到新邮件后触发 VBA 代码运行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18602116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 23:08:13  来源:igfitidea点击:

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

vbaemailoutlookoutlook-vbaoutlook-2013

提问by user2738649

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.

Win 7、Outlook 2013 我使用 VBA 代码对到达我的收件箱的一些文件执行操作。但是,我必须单击/运行按钮才能运行此宏。

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.

我尝试了 Outlook 规则来运行脚本,但没有成功。

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

回答by enderland

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 WithEventson your inbox is probablyyour best bet.

我专门使用我作为规则运行的脚本,应用于所有消息。这使您可以轻松、清晰地访问您收到的邮件。由于您想WithEvents在收件箱中设置的每条消息上运行此程序,这可能是您最好的选择。

For example:

例如:

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

您可以为 Outlook 文件夹创建侦听器,如下所示:

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 ItemAddmethod to each of them like:

然后,您可以将ItemAdd方法分配给每个人,例如:

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.

所有这些代码都可以放在 ThisOutlookSession 中。