Try Catch in VBA

I’ve done a little VBA (Visual basic for applications) programming lately, and today I ran into a problem, where I wanted to make a simple try catch.

The error occurred because the users put letters instead of numbers into a specified field, so I just wanted to do some simple user validation with try catch.

Apparently, there is no such thing as try catch in VBA.

Instead of try, you have to use the”on error” statement. So a Try Catch will look something like this.

”…some code…
On Error GoTo ErrHandler:
”…The code, where you might get a run time error

ErrHandler:
    ” Some error handling code
Resume Next

When an error occurs, the code will jump to the ErrHandler label, and the resume next statement will continue to run the rest of the code.

I guss that is nice to know 🙂

2 thoughts on “Try Catch in VBA

  1. Jørgen Jensen

    det er super smart med denne fejlhåndtering, og ovenikøbet så kan du benytte

    err.number til at tjekke for specifikke fejl under din error handler. På den måde kan du ved hjælp af en selec case eller en if sætning nøjes med at benytte en error handler.

  2. Christian

    Ja try/catch er der ikke meget af i Excel VBA 🙂 Men du kan som du skriver altid bruge

    On Error Goto ErrHandler

    du kan også bruge

    On Error Resume Next

    der bare fortsætter på næste linie – den kan også være ganske nyttig nogle gange 🙂

    Desuden for at slå error håndtering fra igen så bruger du

    On Error Goto 0 (det er nul)

Leave a Reply

Your email address will not be published. Required fields are marked *