如何暂时停止传入电子邮件的事件脚本?

How to temporarily stop event script on incoming emails?

我用

处理收到的电子邮件
Private WithEvents objNewMailItems As Outlook.Items

作为启动程序和

Private Sub objNewMailItems_ItemAdd(ByVal item As Object)

收件箱收到新邮件时执行。

我如何(手动)停止执行此过程?

objNewMailItems 被声明为事件提供者;只要设置了它的引用,它就会触发事件。

要使其停止,您需要将其引用设置为 Nothing

Public Sub StopHandlingNewMailItems()
    Set objNewMailItems = Nothing
End Sub

获取当前正在分配该对象引用的代码,将其移至某个 StartHandlingNewMailItems() 过程,并在启动时调用它;现在您可以随意切换处理新邮件项目 on/off。

如果将多个项目(超过 16 个)添加到文件夹中,可能根本不会触发 ItemAdd 事件。我建议改为处理 Application class 的 NewMailEx 事件。对于 Microsoft Outlook 处理的每个接收项目,此事件都会触发一次。该项目可以是几种不同项目类型中的一种,例如 MailItemMeetingItemSharingItemEntryIDsCollection 字符串包含对应于该项目的条目 ID。

NewMailEx 事件在新邮件到达收件箱时且在客户端规则处理发生之前触发。您可以使用 EntryIDCollection 数组中返回的条目 ID 来调用 NameSpace.GetItemFromID 方法并处理该项目。

Private Sub outApp_NewMailEx(ByVal EntryIDCollection As String)
    if Cancel then
      Dim itm as Outlook.MailItem
      Set itm = NS.GetItemFromID(EntryIDCollection)

      If itm.Class = olMail Then

        Debug.Print "mail received"
        Debug.Print itm.Parent.Parent.name

      End If
    End If
End Sub

要防止 VBA 宏出现在 运行 中,您可以添加一个名为 "CancelButton" 的按钮来设置一个标志,然后在 NewMailEx 事件中检查该标志处理程序。

Bool Cancel
Private Sub CancelButton_OnClick()
    Cancel=True
End Sub

最后,您可能会发现 How to stop VBA code running? post 很有帮助。