发生错误事件时,阻止Outlook VBA在ItemSend()中发送邮件

时间:2018-11-14 01:41:52

标签: vba events outlook onerror

当运行时在ItemSend()事件中发生错误时,将发送Outlook mailitem。在代码中放置Cancel = True并不能阻止这种情况的发生。这是VBA固有的缺陷吗?

我该如何解决这个问题?任何想法都欢迎。

Public WithEvents myApp As Outlook.Application

Sub Initialize_handler()
    Set myApp = Application
End Sub

Private Sub myApp_ItemSend(ByVal Item As Object, Cancel As Boolean)
On Error GoTo ErrorHandler_myApp_ItemSend
    Cancel = True

    ' Do something erroneous

    Exit Sub

ErrorHandler_myApp_ItemSend:
    Cancel = True
    MsgBox "Error: " Err.Description
    Err.Clear
End Sub

2 个答案:

答案 0 :(得分:1)

我没有解释为什么关闭检查器时不发送邮件。

Option Explicit

Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)

    Dim objInsp As Inspector

    On Error GoTo ErrorHandler_Application_ItemSend

    ' Do something erroneous
    Err.Raise 1

    Exit Sub

ErrorHandler_Application_ItemSend:

    Cancel = True
    MsgBox "Error: " & Err.Description

    Set objInsp = Item.GetInspector

    ' Look for the mail in the drafts folder
    objInsp.Close olSave

End Sub

答案 1 :(得分:-1)

您不能使用On Error GoTo来获取错误事件,您可以尝试使用If语句。例如:

Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)

On Error Resume Next

If Not Left(LCase(Item.Subject), 3) = "re:" And Not Left(LCase(Item.Subject), 3) = "fw:" Then
      prompt$ = "You sending this from " & Item.SendUsingAccount & ". Are you sure you want to send it?"
       If MsgBox(prompt$, vbYesNo + vbQuestion + vbMsgBoxSetForeground, "Check Sending Account") = vbNo Then
         Cancel = True
       End If
End If

End Sub

有关更多信息,请参考此链接:

https://3v4l.org/keJ2a

Warn Before Sending Messages to the Wrong Email Address