Excel

Cover Error Handling For Several Macros In One Place

Ease of Use

Intermediate

Version tested with

2000, 2002 

Submitted by:

Jacob Hilderbrand

Description:

This macro demonstrates how to have one Error Handling routine for several macros. 

Discussion:

You have a project with several macros, and find yourself repeating a lot of error handling code for each one. This macro demonstrates how you can conveniently put all your error handling in one macro and call it from all your other macros. 

Code:

instructions for use

			

Option Explicit Sub CreateError1() Dim x As Workbook On Error GoTo error: Set x = Workbooks("dfaksjdfh3u9sdf") MsgBox "Code Will Continue From Here" Exit Sub error: Call ErrorHandler(Err) Resume Next End Sub Sub CreateError2() Dim x As Double On Error GoTo error: x = 1 / 0 MsgBox "Code Will Continue From Here" Exit Sub error: Call ErrorHandler(Err) Resume Next End Sub Sub ErrorHandler(MyErr As ErrObject) Dim Prompt As String Dim Title As String Dim MyResponse As VbMsgBoxResult Prompt = "The following error has occured:" & vbNewLine & _ MyErr.Description & vbNewLine & _ "Do you want to terminate this macro?" Title = "Error" Select Case MyErr.Number Case Is = 9 'Subscript Out Of Range 'Code Here Case Is = 11 'Divide By Zero 'Code Here End Select MyResponse = MsgBox(Prompt, vbYesNo, Title) If MyResponse = vbYes Then 'Code here i.e., 'Application.EnableEvents = True 'More code here End End If On Error GoTo 0 End Sub

How to use:

  1. Open Excel.
  2. Alt + F11 to open the VBE.
  3. Insert | Module.
  4. Paste the code there.
  5. Close the VBE (Alt + Q or press the X in the top-right corner).
 

Test the code:

  1. Tools | Macro | Macros...
  2. Select CreateError1 or CreateError2 and press Run.
 

Sample File:

ErrorHandler.ZIP 8.77KB 

Approved by mdmackillop


This entry has been viewed 225 times.

Please read our Legal Information and Privacy Policy
Copyright @2004 - 2020 VBA Express