Ashonna
Ashonna

Reputation: 47

VBA On Error statement executes without error

I am using the simple code below to handle the error. When there is no error in why does the msgbox appears? How can I make the msgbox appear only when there is an error?

Sub Test()
On Error GoTo ErrHandler
On Error GoTo 0


'rest of the code is here

ErrHandler:
MsgBox "Please make sure the file exists in the current folder."
Exit Sub
End Sub

Upvotes: 2

Views: 63

Answers (1)

BigMike
BigMike

Reputation: 6863

You should add an exit before the actual error handler and restore the default error handling after having shown the dialog. (The 1st on error goto 0 is probably misplaced).

Sub Test()
On Error GoTo ErrHandler


'rest of the code is here

'Exit before error handlers
Exit Sub

ErrHandler:
  MsgBox "Please make sure the file exists in the current folder."
  ' Reset error handler
  On Error GoTo 0
  Exit Sub
End Sub

Upvotes: 4

Related Questions