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.
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.
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.
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.”
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With