tags:

views:

64

answers:

3

Hi, Can somebody explain me what this code means ? I guess its if an error occurs go to section ErrHandler, but why is there a resume next at the end and Exit sub inbetween ?

On Error Goto ErrHandler:
N = 1 / 0    ' cause an error
'
' more code
'
Exit Sub
ErrHandler:
' error handling code
Resume Next
End Sub 

I also wrote a short code to get a better understanding. If you run it in VBA excel you will get 4 numbers that pops up in order : 1,2,2,4 I understand the first 2 numbers , but why is the third number 2 and the last one 4 ? btw for this example no error occured .

On Error Goto Err:
n = 1
MsgBox n
Err:
n = 2
MsgBox n
Resume Next
MsgBox 4

Resume Next
End Sub 
+1  A: 

It picks up execution of the method body at the point after where the error occured.

David M
A: 

From the On Error documentation:

Specifies that when a run-time error occurs, control goes to the statement immediately following the statement where the error occurred, and execution continues from that point.

John Feminella
+1  A: 

It has already been said that Resume Next will pick up execution at the point after the error occurred. There is also Resume, which picks up execution starting with the line that caused the error and Resume , which picks up execution at a specified label.

So, this is what happens in the code you provided:

  1. N = 1 / 0 raises a divide by zero error
  2. execution is moved to the ErrHandler label.
  3. Error handling code will run till it reaches Resume Next.
  4. Resume next will move execution to the line after N = 1/0. Since you are going back it makes sense that your error handling code might do something like this N = 1, otherwise the rest of the code will try to use N which is uninitialized and you will get another error.

The following link provides a simple explanation oerror handling and the three resume statements:

http://www.cpearson.com/excel/ErrorHandling.htm

Waleed Al-Balooshi
Hi Waleed , what happens if no error occured , what effect does resume next take ?
excel34
If you look at the first snippet of code that you provided there is an "Exit Sub" before the error handler label. If you don't encounter an error this line will exit the procedure without running any of the lines of code following it including the Resume Next statement. Thus Resume Next doesn't do anything here if there are no errors.
Waleed Al-Balooshi