error handling

  • Thread starter James Cornthwaite
  • Start date
J

James Cornthwaite

Could somebody please explain what the following fragment of code does with
a function i've seen.


.............................
On error resume next

cellreference.comment.delete

on error goto 0

..................


goto ??????


I think i'm correct in thinking the "on error resume next" statement means
any errors after this statement and before the end of the function should be
ignored.
for example caused by the delete of a non existent comment.

But whats the goto all about?

Thanks
James
 
H

Harald Staff

Hi James

Goto is the ability to jump to specific named ranges of your code, usually
done like

Sub test1()
On Error GoTo MyError
MsgBox 45 / 0
Exit Sub
MyError:
MsgBox "snafu"
End Sub

Extensive use of Goto makes so called "spaghetti code", amateur code totally
impossible to read and manintain. Like

Sub test2()
Dim i As Long
i = Val(InputBox("Number:"))
If i = 0 Then GoTo C
A:
MsgBox "You said " & i
If i > 10 Then GoTo D
B:
MsgBox "i is now " & i
Exit Sub
C:
MsgBox "Hi C"
GoTo A
D:
i = i / 5
GoTo B
End Sub

The only reasonable use of goto is what I showed in test1; if something
happens then jump to the end and do the cleanup there. Avoid spaghetti.

Goto 0 cancels all previous error handling and lets the application take
care of it instead. As in

Sub test3()
On Error GoTo MyError
MsgBox 45 / 1
On Error GoTo 0
MsgBox 45 / 0
Exit Sub
MyError:
MsgBox "snafu"
End Sub

HTH. Best wishes Harald
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top