如何在VBA错误处理发送告警邮件后返回错误代码行并暂停以进行调试?
How to Send Error Alert Email and Pause at the Error Line in VBA
Absolutely, you can tweak your error handling routine to send the alert email first, then jump right back to the exact line where the error occurred and pause execution for debugging. Here's the modified code with clear explanations:
On Error GoTo ErrorHandler: ' Your main code goes here ' Example test code to trigger an error: ' Dim myVar As Integer ' myVar = 1 / 0 ' This will throw a division-by-zero error Exit Sub ErrorHandler: ' Set up and send the error notification email Dim OutApp As Object Dim OutMail As Object Set OutApp = CreateObject("Outlook.Application") Set OutMail = OutApp.CreateItem(0) With OutMail .To = "hamza.ali@telus.com" .Subject = "Error Occurred - Error Number " & Err.Number .Body = "We have found an error with the bot. Please open the VM to debug the problem." & vbCrLf & _ "Error Description: " & Err.Description & vbCrLf & _ "Error Source: " & Err.Source .Display ' Replace with .Send to auto-send the email without preview End With Debug.Print "Error Caught: " & Err.Description & " | Source: " & Err.Source ' Clean up Outlook objects to avoid lingering instances Set OutMail = Nothing Set OutApp = Nothing ' Re-raise the error to trigger the debugger at the original error line ' This will pause execution exactly where the error happened Err.Raise Err.Number, Err.Source, Err.Description End Sub
Key Changes & Why They Work:
- Descriptive error label: Renamed
xtoErrorHandlerfor better code readability. - Formatted email body: Added
vbCrLfto split error details into separate lines, making the email easier to scan. - Re-raise the error with
Err.Raise: After sending the email, this line tells VBA to throw the exact same error again. When this happens:- If your VBA editor is set to the default "Break on Unhandled Errors" setting, it will pause execution directly at the line where the original error occurred.
- You can inspect variables, check the call stack, and debug without re-running hundreds of lines of code.
Quick Setup Check:
Make sure your VBA editor's error handling is configured correctly to get the most out of this:
- Go to
Tools > Options > General - Select "Break on Unhandled Errors" (this is the default, but double-check it's enabled)
内容的提问来源于stack exchange,提问作者Hammy
相关产品推荐
相关产品推荐

