如果错误,则跳过发送电子邮件

时间:2015-09-30 14:29:10

标签: vba excel-vba email excel

我有一段代码在按下按钮时向我发送电子邮件。 但是,如果出于某种原因,电子邮件不会发送,我不希望代码中断,我希望它只是忽略此命令并继续。如何将其添加到我当前的代码中?

Dim OutApp As Object
Dim OutMail As Object
Dim strbody As String

Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)

strbody = ThisWorkbook.Name & vbNewLine & _
          Environ("username")
On Error Resume Next
With OutMail
    .To = "bm@Email.co.uk"
    .CC = ""
    .BCC = ""
    .Subject = "OGI Statements Used"
    .Body = strbody
    .Send
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing

谢谢

1 个答案:

答案 0 :(得分:3)

您可以更改错误语句以避免在之前错误的情况下使用.Send方法 - 但如果在实际发送电子邮件时发生错误则不会有太多错误你可以这样做,因为执行已经移交给另一个应用程序,所以它可以说是错误处理程序的范围。

看看这是否有用:

On Error GoTo Skip:
With OutMail
    .To = "bm@Email.co.uk"
    .CC = ""
    .BCC = ""
    .Subject = "OGI Statements Used"
    .Body = strbody
    .Send
End With
Skip:
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing