excel 有没有办法回到错误行并停止?

ni65a41a  于 2023-01-03  发布在  其他
关注(0)|答案(1)|浏览(313)

我正在写VBA代码的错误处理。
我想让它在代码失败时给我发一封电子邮件:

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行代码来查看错误发生在哪里。

unhi4e5o

unhi4e5o1#

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键,转到导致错误的行
  • 变量保存在内存中,因此您可以调试

相关问题