我需要在outlook中创建某种触发器,在收件箱中收到新电子邮件时将执行python脚本。我确实参考了这个链接:How do I trigger a macro to run after a new mail is received in Outlook?并编写了以下脚本:
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 test_macro(ByVal item As Object)
On Error GoTo ErrorHandler
Dim Msg As Outlook.MailItem
If TypeName(item) = "MailItem" Then
Set Msg = item
Ret_Val = Shell("python <path-of-python-script>")
Debug.Print "Value: ", Ret_Val
If Ret_Val <> 0 Then
MsgBox "Couldn't run python script", vbOKOnly
End If
End If
ProgramExit:
Exit Sub
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description
Resume ProgramExit
End Sub
虽然它没有给出任何错误但是由于某些原因我的python脚本没有执行。我已相应地在Outlook中配置了宏设置,并根据可用文档创建了新规则。但仍然无法达到预期的效果。
感谢任何帮助。
答案 0 :(得分:0)
您需要将test_macro
子重命名为Items_ItemAdd
。在您复制代码的答案中使用该名称是有原因的。 Items_ItemAdd
表示sub是ItemAdd
对象事件的事件处理程序,名为Items
。
几个笔记:
ThisOutlookSession
模块并重新启动Outlook以对其进行初始化。该代码不会在标准模块中工作。Private WithEvents Items As Outlook.Items
。令人困惑。完全按照我粘贴的方式尝试以下代码。 (我保留了令人困惑的变量名称。)
<强> ThisOutlookSession: 强>
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
MsgBox "Items_ItemAdd listener initialized."
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
MsgBox "Python script will run now."
Ret_Val = Shell("python <path-of-python-script>")
Debug.Print "Value: ", Ret_Val
If Ret_Val <> 0 Then
MsgBox "Couldn't run python script", vbOKOnly
End If
End If
ProgramExit:
Exit Sub
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description
Resume ProgramExit
End Sub