vba 在 Outlook 中收到新邮件后,如何触发宏运行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11263483/
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
How do I trigger a macro to run after a new mail is received in Outlook?
提问by Gautam Mainkar
I'm writing a macro that creates tickets on a database based on alerts received from a Nagios server as an email. However, I cannot let the macro run in an infinite loop while checking for mails because it is just too resource heavy and makes my desktop hang. I need to find a way to trigger the macro only when a new mail is received.
我正在编写一个宏,它根据从 Nagios 服务器作为电子邮件收到的警报在数据库上创建票证。但是,我不能让宏在检查邮件时无限循环运行,因为它资源太重并且使我的桌面挂起。我需要找到一种仅在收到新邮件时触发宏的方法。
I looked for something along the lines of NewMail events on the MSDN website, but I can't find anything coherent. Can anyone show me just a bit of sample code to show how to trigger macros from new mail events?
我在 MSDN 网站上寻找与 NewMail 事件类似的内容,但找不到任何一致的内容。谁能给我看一些示例代码来展示如何从新邮件事件中触发宏?
回答by JimmyPena
This code will add an event listener to the default local Inbox, then take some action on incoming emails. You need to add that action in the code below.
此代码将向默认的本地收件箱添加一个事件侦听器,然后对传入的电子邮件执行一些操作。您需要在下面的代码中添加该操作。
Private WithEvents Items As Outlook.Items
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
If TypeName(item) = "MailItem" Then
Set Msg = item
' ******************
' do something here
' ******************
End If
ProgramExit:
Exit Sub
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description
Resume ProgramExit
End Sub
After pasting the code in ThisOutlookSession
module, you must restart Outlook.
在ThisOutlookSession
模块中粘贴代码后,您必须重新启动 Outlook。
回答by Alistair Weir
Try something like this inside ThisOutlookSession
:
在里面尝试这样的事情ThisOutlookSession
:
Private Sub Application_NewMail()
Call Your_main_macro
End Sub
My outlook vba just fired when I received an email and had that application event open.
当我收到一封电子邮件并打开该应用程序事件时,我的 Outlook vba 刚刚启动。
Edit: I just tested a hello world msg box and it ran after being called in the application_newmail
event when an email was received.
编辑:我刚刚测试了一个 hello world msg 框,它在application_newmail
收到电子邮件时被调用后运行。