【问题标题】:Is there a way to go back to the error line and stop?有没有办法回到错误行并停止?
【发布时间】:2021-09-11 17:40:36
【问题描述】:

所以我正在编写一个用于错误处理的 VBA 代码,我希望它在 Bot 失败时向我发送一封电子邮件,如下所示:

On Error GoTo x:

'main code

 Exit Sub

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

           With OutMail
            .To = "hamza.ali@telus.com"
            .Subject = "Error Occured - Error Number " & Err.Number
            .Body = "We have found an error with the bot. Please open the VM to debug the problem. -->" & Err.Description & " And the reason is: " & Err.Source

            .Display '~~> Change this to .Send for sending the email
          End With
        Debug.Print "x -" & Err.Description & Err.Source
        Set OutApp = Nothing: Set OutMail = Nothing
         End Sub

我希望有一种方法可以通过此错误处理方法发送电子邮件,然后返回错误行并停止。这样当我尝试调试时,我知道错误发生在哪一行,并且可以尝试修复它,而不是再次运行 100 行代码来查看错误发生的位置。

【问题讨论】:

  • On error goto 0: Resume?

标签: excel vba error-handling outlook


【解决方案1】:
Sub TestMe()

    On Error GoTo TestMe_Error:
    
    Dim foo As Long
    foo = 5
    Dim bar As Long
    bar = 10
    Debug.Print foo / bar
    Debug.Print foo / 0   '<- Div/0 error
    Debug.Print foo / 10
    
    On Error GoTo 0
    Exit Sub
    
TestMe_Error:
    
    Debug.Print Err.Description & " " & Err.Number
    Stop
    Resume

End Sub
  • Stop 行的错误处理程序中停止
  • 然后使用 F8 会转到导致错误的确切行
  • 变量保存在内存中,方便调试

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-25
    • 2021-01-14
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-10
    • 1970-01-01
    相关资源
    最近更新 更多