如有任何错误,仅发送一封自动电子邮件

时间:2019-10-17 15:30:42

标签: excel vba

我有执行多项任务的代码,并且希望收到有关任何错误的电子邮件通知。我当前的代码工作正常,但我注意到有时会收到2或3条消息。为什么会发生这种情况以及如何解决?

Sub PerformAll()

    On Error GoTo ErrorHandler

            Call RefreshQuery
            Call FormatAllCells
            Call BuildListWithClass

            Exit Sub

ErrorHandler:

    If Err <> 0 Then
            Dim objOutlook As Object
            Set objOutlook = CreateObject("Outlook.Application")

            ' CREATE EMAIL OBJECT.
            Dim objEmail As Object
            Set objEmail = objOutlook.CreateItem(olMailItem)

            With objEmail
                .To = "me.you@company.com"
                .Subject = "There was an error with Importer"
                .Body = "Hello Sir, there was an error with Importer. Please take a look!"
                .Send
            End With

            ' CLEAR.
            Set objEmail = Nothing
            Set objOutlook = Nothing
    End If

    Resume Next

End Sub

1 个答案:

答案 0 :(得分:0)

好像删除了Resume Next一样

当前代码:

Sub PerformAll()

    On Error GoTo ErrorHandler

            Call RefreshQuery
            Call FormatAllCells
            Call BuildListWithClass

            Exit Sub

ErrorHandler:

    If Err <> 0 Then
            Dim objOutlook As Object
            Set objOutlook = CreateObject("Outlook.Application")

            ' CREATE EMAIL OBJECT.
            Dim objEmail As Object
            Set objEmail = objOutlook.CreateItem(olMailItem)

            With objEmail
                .To = "me.you@company.com"
                .Subject = "There was an error with Importer"
                .Body = "Hello Sir, there was an error with Importer. Please take a look!"
                .Send
            End With

            ' CLEAR.
            Set objEmail = Nothing
            Set objOutlook = Nothing
    End If

End Sub