【问题标题】:Outlook VBA Code stops firing after some timeOutlook VBA 代码在一段时间后停止触发
【发布时间】:2022-02-23 22:09:17
【问题描述】:

下面的代码完美运行:

Option Explicit

Dim myOlApp As New Outlook.Application

Public WithEvents myOlInspectors As Outlook.Inspectors

Private Sub Application_Startup()
    Initialize_handler
End Sub

Public Sub Initialize_handler()
    Set myOlInspectors = myOlApp.Inspectors
End Sub

Private Sub myOlInspectors_NewInspector(ByVal Inspector As Outlook.Inspector)
    Dim msg As Outlook.MailItem
If Inspector.CurrentItem.Class = olMail Then
    Set msg = Inspector.CurrentItem
    If msg.Size = 0 Then
        'MsgBox "New message"             ' TEST LINE
            msg.CC = "email@email.com"
    End If
End If
End Sub

但是,经过几个小时的工作。它突然停止发射(我没有收到任何错误)。

我对代码有什么误解吗?

是否有关于 Outlook.Inspectors 的问题,导致它由于某种原因停止启动?

【问题讨论】:

标签: vba events outlook


【解决方案1】:

如果当前没有项目打开,您的事件方法可能会失败。

要添加CC 收件人,您应该执行类似的操作

Set myRecipient = msg.Recipients.Add("email@email.com") 
 
myRecipient.Type = olCC

Documentation

【讨论】:

    【解决方案2】:

    很可能该事件已正确触发,但您在运行时的代码中出现错误。 NewInspector 事件不是获取CurrentItem 属性的最佳位置:

    Private Sub myOlInspectors_NewInspector(ByVal Inspector As Outlook.Inspector)
        Dim msg As Outlook.MailItem
    If Inspector.CurrentItem.Class = olMail Then
        Set msg = Inspector.CurrentItem
        If msg.Size = 0 Then
            'MsgBox "New message"             ' TEST LINE
                msg.CC = "email@email.com"
        End If
    End If
    

    尤其是以下代码行可能会在运行时引发错误:

    If Inspector.CurrentItem.Class = olMail Then
    

    相反,请考虑使用第一个 Inspector 的 Activate 事件,当检查器成为活动窗口时触发,无论是作为用户操作的结果还是通过程序代码。因此,在第一个 Activate 事件中,您可以毫无问题地获取项目的属性。

    您也可以考虑在代码中添加On Error statement,这样您就可以知道为什么事件“没有被触发”。

    【讨论】: