On Error Vba Excel Handling
Contents |
three flavors: compiler errors such as undeclared variables that prevent your code from compiling; user data entry error such as a user entering a negative value where only excel vba try catch a positive number is acceptable; and run time errors, that occur when VBA
Vba Error Handling Best Practices
cannot correctly execute a program statement. We will concern ourselves here only with run time errors. Typical run time vba error handling in loop errors include attempting to access a non-existent worksheet or workbook, or attempting to divide by zero. The example code in this article will use the division by zero error (Error 11) when on error goto line we want to deliberately raise an error. Your application should make as many checks as possible during initialization to ensure that run time errors do not occur later. In Excel, this includes ensuring that required workbooks and worksheets are present and that required names are defined. The more checking you do before the real work of your application begins, the more stable your application
Vba On Error Exit Sub
will be. It is far better to detect potential error situations when your application starts up before data is change than to wait until later to encounter an error situation. If you have no error handling code and a run time error occurs, VBA will display its standard run time error dialog box. While this may be acceptable, even desirable, in a development environment, it is not acceptable to the end user in a production environment. The goal of well designed error handling code is to anticipate potential errors, and correct them at run time or to terminate code execution in a controlled, graceful method. Your goal should be to prevent unhandled errors from arising. A note on terminology: Throughout this article, the term procedure should be taken to mean a Sub, Function, or Property procedure, and the term exit statement should be taken to mean Exit Sub, Exit Function, or Exit Property. The term end statement should be taken to mean End Sub , End Function, End Property, or just End. The On Error Statement The heart of error handling in VBA is the On Error statement. This stateme
generally put more focus on the coding part and getting the desired result but during this process we forget an important thing i.e. Error handling. Error handling is an important part of every code and VBA On vba error number Error Statement is an easy way for handling unexpected exceptions in Excel Macros. A well vba on error goto 0 written macro is one that includes proper exception handling routines to catch and tackle every possible error. Error handling is important because in
Vba On Error Msgbox
case of any unexpected exceptions your code doesn’t break. Even if any fatal unexpected error occurs in the code then also you should ensure that the code should terminate gracefully. Definition of VBA On Error Statement: On Error http://www.cpearson.com/excel/errorhandling.htm statement instructs VBA Compiler, what to do in case any runtime exception are thrown. Syntax of On Error Statement: Basically there are three types of On Error statement: On Error Goto 0 On Error Resume Next On Error Goto
execution at a specified line upon hitting an error. Situation: Both programs calculate the square root of numbers. Square Root 1 Add the following code lines to the 'Square Root 1' command button. 1. First, we declare two Range objects. We call http://www.excel-easy.com/vba/examples/error-handling.html the Range objects rng and cell. Dim rng As Range, cell As Range 2. We initialize the Range object rng with the selected range. Set rng = Selection 3. We want to calculate the square root of each cell in http://www.consultdmw.com/excel-macro-error-handling.htm a randomly selected range (this range can be of any size). In Excel VBA, you can use the For Each Next loop for this. Add the following code lines: For Each cell In rng Next cell Note: rng and cell on error are randomly chosen here, you can use any names. Remember to refer to these names in the rest of your code. 4. Add the following code line to the loop. On Error Resume Next 5. Next, we calculate the square root of a value. In Excel VBA, we can use the Sqr function for this. Add the following code line to the loop. cell.Value = Sqr(cell.Value) 6. Exit the Visual Basic Editor and test the program. Result: Conclusion: Excel VBA has vba on error ignored cells containing invalid values such as negative numbers and text. Without using the 'On Error Resume Next' statement you would get two errors. Be careful to only use the 'On Error Resume Next' statement when you are sure ignoring errors is OK. Square Root 2 Add the following code lines to the 'Square Root 2' command button. 1. The same program as Square Root 1 but replace 'On Error Resume Next' with: On Error GoTo InvalidValue: Note: InvalidValue is randomly chosen here, you can use any name. Remember to refer to this name in the rest of your code. 2. Outside the For Each Next loop, first add the following code line: Exit Sub Without this line, the rest of the code (error code) will be executed, even if there is no error! 3. Excel VBA continues execution at the line starting with 'InvalidValue:' upon hitting an error (don't forget the colon). Add the following code line: InvalidValue: 4. We keep our error code simple for now. We display a MsgBox with some text and the address of the cell where the error occurred. MsgBox "can't calculate square root at cell " & cell.Address 5. Add the following line to instruct Excel VBA to resume execution after executing the error code. Resume Next 6. Exit the Visual Basic Editor and test the program. Result: Do you like this free website? Please share this page on Google+ 3/6 Completed! Lea
map Error Trapping and Handling in Excel Macros Errors occur during the execution of a macro due to a variety of reasons including the use of incorrect code and the macro being executed under circumstances for which it was not intended. Including error trapping in all your macros allows you to determine what happens in the event of any error. You gain control of the error and are in a position to take appropriate action without your users getting wind of there being anything wrong. Failure to include error handling may result in unwelcome and confusing Excel behaviour. At the very least, your users might be dumped out of their spreadsheet and into your code in the Visual Basic Editor, facing for them some bewildering error messages from Excel. At worst you could be faced with loss of recent changes to a spreadsheet or with Excel freezing and refusing to function at all. Simple Error Handler There are a number of ways in which you might choose to include code for error handling in a macro. This is the skeleton code for a simple way: Sub your_macro_name() ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ On Error Goto ErrorHandler your macro code here ProcedureDone: Exit Sub ErrorHandler: MsgBox Err.Number & ": " & Error.Description Resume ProcedureDone End Sub The On Error statement turns on error trapping. Information about any error that occurs subsequent to line 3 is stored in a VBA error object named 'Err'. In the event of an error, the On Error Goto ErrorHandler statement instructs the macro to stop executing your code at the point at which the error occurs and to pick again at the ErrorHandler label, line 9. Line 10 sends a message box to the screen displaying information about the nature of the error: Err.Number is a unique identification number for the error object drawn from VBA's library of errors Error.Description is a description of that error. Line 11 instructs the macro to resume executing at the ProcedureDone label on line 6. Refined Error Handling Code Let's assume you have wrapped a new macro in the error-handling code described above. As you test your macro an error results. Therefore you are presented with the message box from which you learn the error number and the nature of the error. Now you are in a position to revise your error handler to respond to this specific error (in this example the error number 1234): Sub your_macro_name() ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ On Error Goto ErrorHandler your macro code here ProcedureDone: Exit Sub ErrorHandler: Select Case Err.Number Case 1234 your code for handling error 1234 Case Else ' All outstanding errors