【问题标题】:Launching Python script with arguments from VBA in Outlook在 Outlook 中使用来自 VBA 的参数启动 Python 脚本
【发布时间】:2021-09-26 06:50:38
【问题描述】:

我正在尝试在将电子邮件移动到某个文件夹时触发 Python 脚本。

这个想法是在 Outlook 中设置一个规则,当电子邮件包含某些关键字时将其移动到特定文件夹,然后在将新项目添加到文件夹时让 VBA 脚本启动带有参数的 Python 脚本。我关注this guide.

Option Explicit
Private objNS As Outlook.NameSpace
Private WithEvents objItems As Outlook.Items

Private Sub Application_Startup()
    Dim objWatchFolder As Outlook.Folder
    Set objNS = Application.GetNamespace("MAPI")

    Set objWatchFolder = objNS.GetDefaultFolder(olFolderInbox)
    Set objItems = objWatchFolder.Items

    Set objWatchFolder = Nothing
End Sub


Private Sub objItems_ItemAdd(ByVal Item As Object)
    MsgBox "Message subject: " & Item.Subject & vbcrlf & "Message sender: " & Item.SenderName &" (" & Item.SenderEmailAddress & ")"
    Dim subject As Item.subject
    Shell("""C:\Path\to\python.exe"" ""C:\Path\With Spaces\script.py """ & subject)
    Set Item = Nothing
End Sub

以前,在使用 Dim subject As Item.subject 声明主题变量后,以下工作有效:

Shell("""C:\path\to\python.exe"" ""C:\Path\With Spaces\To\Script\Hello.py """ & subject)

现在我得到一个编译错误

用户定义类型未定义。

此错误发生在Dim subject As Item.subject 行。

当我尝试通过以下方式将电子邮件的主题传递给 Python 脚本时:

Shell("""C:\path\to\python.exe"" ""C:\Path\With Spaces\To\Script\Hello.py """ & Item.subject)

它没有崩溃,但看起来 Python 脚本从未运行过。

当我这样做时:

Shell("""C:\path\to\python.exe"" ""C:\Path\With Spaces\To\Script\Hello.py "" & Item.subject")

它将 &Item.subject 作为字符串参数传递 - 存储在 Item.subject 中的电子邮件主题没有传递,而是文字字符串“Item.subject”。

为什么Dim subject As Item.subject 现在会导致错误?如何将电子邮件的主题作为参数传递给我的 Python 脚本?

【问题讨论】:

标签: python vba outlook


【解决方案1】:

我认为您的问题是不正确的双引号分配和调用 python 代码的间距。我还假设主题中可以有空格,所以应该用双引号引起来(假设我有正确的命名法):

"""C:\Path\to\python.exe"" ""C:\Path\With Spaces\script.py"" """ & Item.subject & """"

在调用运行 python 脚本之前,您可以使用 Debug.Print 来检查字符串是否符合预期。免责声明:我没有使用过 python 脚本,所以这是未经测试的

Option Explicit
Private WithEvents objItems As Outlook.Items

Private Sub Application_Startup()
    With Application.Outlook
        Set ObjItems = .GetNamespace("MAPI").GetDefaultFolder(olFolderInbox).Items
    End With
End Sub

Private Sub objItems_ItemAdd(ByVal Item As Object)
    If TypeName(Item) = "MailItem" Then
        Dim strFunc As String: strFunc = """C:\Path\to\python.exe"" ""C:\Path\With Spaces\script.py"" """ & Item.subject & """"
        Debug.Print strFunc
        Shell strFunc, vbMinimizedNoFocus
    End If
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-29
    • 1970-01-01
    • 1970-01-01
    • 2021-09-13
    • 2018-12-04
    • 1970-01-01
    • 2013-06-26
    • 2018-07-01
    相关资源
    最近更新 更多