Why "on error resume next" and "on error goto 0" have to be placed where they are in this sub?

Hi,

 

Below is a simple sub to get user selected range - this is an example from John Walkenbach's book.

 

What I can't understand here is that why in this program, "On error resume next" and "On error goto 0" have to be placed exactly where they are. I tried to place these two statements in different places within the procedure, then I got errors. Please explain your thoughts - think about those early days when you just started to learn VBA did this kind of question bother you as well?

 

Apologies if this question sounds stupid to you. And, thanks!

_____________________________________________________________________

Sub GetUserRange()
    Dim UserRange As Range
   
    Prompt = "Select a range for the random numbers."
    Title = "Select a range"

'   Display the Input Box
    On Error Resume Next
 
    Set UserRange = Application.InputBox( _
        Prompt:=Prompt, _
        Title:=Title, _
        Default:=ActiveCell.Address, _
        Type:=8) 'Range selection
   
    On Error GoTo 0

'   Was the Input Box canceled?
    If UserRange Is Nothing Then
        MsgBox "Canceled."
    Else
        UserRange.Formula = "=RAND()"
    End If
End Sub

___________________________________________________________________________

 

Question Info


Last updated April 2, 2019 Views 4,333 Applies to:
Answer
Answer
The On Error GoTo 0 is the default behaviour when a VBA macro encounters an error. The On Error Resume Next signals the VBA engine skip over an error and continue processing subsequent commands. This is necessary as exiting the InputBox with Cancel will result in the Set command throwing an error and halt the macro without it. After that potential error has been handled, On Error GoTo 0 is specified to restore default error handling.

Edit: modified some verbage

2 people were helped by this reply

·

Did this solve your problem?

Sorry this didn't help.

Great! Thanks for marking this as the answer.

How satisfied are you with this reply?

Thanks for your feedback, it helps us improve the site.

How satisfied are you with this response?

Thanks for your feedback.