Hammy
Hammy

Reputation: 13

Is there a way to go back to the error line and stop?

I am writing VBA code for error handling.

I want it to send me an email when the code fails:

On Error GoTo x:
'main code
Exit Sub

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

     With OutMail
          .To = "[email protected]"
          .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

I want to send an email through this error handle method then go back to the error line and stop. When I am trying to debug I would know on which line the error happened and need not run the 100 lines of code to see where the error happened.

Upvotes: 1

Views: 79

Answers (1)

Vityata
Vityata

Reputation: 43585

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
  • stops in the error handler on the Stop line
  • then with F8 it goes to the exact line, that has caused the error
  • variables are kept in the memory, so you can debug

Upvotes: 2

Related Questions