Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manage the no error case when handling errors in VBA?

I need to catch some VBA errors using the GoTo statement:

Sub mySub
 On Error GoTo errorHandler:
    Workbooks.Open("myWorkbook")
'
' Some Code
'
errorHandler:
MsgBox "ERROR"

End Sub

The problem is that when there is no error the errorHandler section is executed.
I found this discussion but the answer doesn't solve my issue.
I tried adding an Exit Sub statement as explained :

Sub mySub
 On Error GoTo errorHandler:
    Workbooks.Open("myWorkbook")
    Exit Sub

'
' Some Code
'
errorHandler:
  MsgBox "ERROR"

End Sub

In this case it exits the method when there is no error. I also tried :

 Sub mySub
 On Error GoTo errorHandler:
    Workbooks.Open("myWorkbook")
'
' Some Code
'
errorHandler:
  MsgBox "ERROR"
  Exit Sub
End Sub

But still the same issue: The errorHandler is executed even when no errors occur.

like image 214
M3HD1 Avatar asked Apr 13 '12 12:04

M3HD1


People also ask

How do I fix type mismatch error in VBA?

Step 1: Write the subprocedure for VBA Type Mismatch. Step 2: Again assign a new variable, let's say “A” as Byte data type. Let's understand the Byte Data type here. Byte can only store the numerical value from 0 to 255.

How do you escape an error in VBA?

On Error Exit Sub In the above code, you have an error handler, “iError” with a message box and then the “Exit Sub” Statement. When an error occurs during the calculation, the goto statement jumps to the error handler (VBA Error Handling), and it will exit the procedure.

How do I fix an overflow error in VBA?

The data type Byte can hold values from 0 to 255. So it causes an error. To fix the error, we either change the data type or reduce the value assigned to the variable “Number.”


1 Answers

Just put Exit sub in.

Sub mySub
 On Error GoTo myHandler:
    Workbooks.Open("myWorkbook")
'
' Some Code
'
Exit sub

myHandler:
MsgBox "EROOR !"

err.clear
End Sub
like image 86
Fionnuala Avatar answered Nov 15 '22 21:11

Fionnuala