VBA has no native vba try catch statement. You get the same result with On Error GoTo: put a label below your code, send errors to it, read the Err object to see what failed, then use Resume, Resume Next or Exit Sub to recover or stop. Add F8, breakpoints and the Immediate window to find the cause.
Last updated: November 2026
Key takeaways
- VBA has no Try, Catch or Finally keywords, but On Error GoTo plus a label gives you the same structure in about 8 lines.
- On Error Resume Next hides every error after it, so switch it off with On Error GoTo 0 as soon as the risky line is done.
- The Err object holds Err.Number, Err.Description and Err.Source, and Err.Clear or any Resume resets it.
- Press F8 to step through code one line at a time, F9 to set a breakpoint and Ctrl+G to open the Immediate window.
- If you would rather read finished, working macros than write from scratch, the Excel VBA Tools & Utilities Pack ($63.99) has 8 VBA applications with editable source.
Launch offerRecord, read and write your own Excel macros and UserForms, and use AI assistants as your VBA tutor without trusting them blindly. 6h 12m of video by PK, with practice files and a capstone.
VBA error handling statements compared
Every statement below controls what VBA does after a run-time error. This table is the quick reference, and the sections after it explain each one with code.
| Statement | What it does | Closest Try/Catch idea | Use it when |
|---|---|---|---|
| On Error GoTo Label | Jumps to a label when an error occurs | catch block | You want to show a message, log the error or clean up |
| On Error Resume Next | Ignores the error and runs the next line | empty catch | One line may fail and you check Err right after it |
| On Error GoTo 0 | Turns error handling off in the procedure | end of try | You want VBA’s own error dialog again |
| On Error GoTo -1 | Clears the active error state | none | You need to reset handling inside a handler |
| Resume | Retries the line that failed | retry | The handler fixed the cause, for example a missing folder |
| Resume Next | Continues at the line after the failure | skip and continue | The failed step is optional |
| Resume Label | Continues at a named line | finally | Cleanup must run on success and on failure |
| Err.Raise | Creates an error on purpose | throw | Your own validation fails and the caller must know |
Is there a VBA try catch in Excel?
No. Microsoft never added Try, Catch or Finally to VBA. The language dates from the Visual Basic 6 era, and its error model is the older On Error statement. Excel 2016, 2019, 2021 and Microsoft 365 on Windows all use that same model.
The workaround is a pattern, not a trick. The code you want to protect is the try block. A label further down the procedure is the catch block. A second label, reached by Resume, plays the part of finally. Once you see the three parts, a vba try catch is only a layout habit.
This differs from languages such as C# or Python, where an exception unwinds the call stack automatically. In VBA, if the current procedure has no handler, the error moves up to the caller, then its caller, and so on. If no procedure in the chain has a handler, Excel shows the standard run-time error dialog with End, Debug and Help buttons. That dialog is what your users see when VBA error handling is missing.
Microsoft documents the statement on its On Error statement reference page, which is worth bookmarking for the exact syntax rules.
How do you write a VBA try catch with On Error GoTo?
Follow these numbered steps. The skeleton at the end is the one to copy.
- Turn on Option Explicit. Put it at the top of every module so a typo in a variable name becomes a compile error instead of a silent bug. In the VBE, Tools, Options, Require Variable Declaration sets it for new modules.
- Write the On Error line first. Place On Error GoTo Catch as the first executable line of the procedure, after the Dim statements.
- Write the normal code. This is your try block. Keep it in the order the work happens.
- End the success path. Add Exit Sub (or Exit Function) before the label. Without it, VBA runs straight into the handler even when nothing went wrong, which is the most common beginner bug.
- Write the label. A label is a name followed by a colon at the start of a line, such as Catch:
- Handle the error. Read Err.Number and Err.Description, tell the user, log it, then leave or resume.
Here is the smallest working version:
Sub TryCatchBasic()
On Error GoTo Catch
Dim total As Double
total = 100 / Range("B1").Value ' fails if B1 is 0
Range("B2").Value = total
Exit Sub
Catch:
MsgBox "Error " & Err.Number & ": " & Err.Description, vbExclamation
End SubIf B1 holds 0, VBA raises error 11 (Division by zero), jumps to Catch and shows the message. If B1 holds 4, B2 receives 25 and the procedure exits before the handler.
How do you add a Finally block in VBA?
Finally means code that runs whether or not an error happened. In VBA you build it with a label that both paths reach. The success path falls into it, and the handler sends control there with Resume.
Sub TryCatchFinally()
On Error GoTo Catch
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
' try: risky work here
Worksheets("Data").Range("A1:A1000").Sort _
Key1:=Worksheets("Data").Range("A1"), Order1:=xlAscending
Finally:
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Exit Sub
Catch:
MsgBox "Sort failed: " & Err.Description, vbExclamation
Resume Finally
End SubThe Finally label matters because a crash with ScreenUpdating set to False leaves Excel looking frozen. Restoring settings in one place means they are restored every time.
What do Resume, Resume Next and On Error GoTo 0 do?
These are the three statements people confuse most. They look similar, but they do different jobs.
Resume (retry the failed line)
Resume goes back to the exact line that raised the error and runs it again. Use it only after the handler has changed something, otherwise you create an infinite loop. A safe version counts attempts:
Sub RetryOnce()
Dim attempts As Long
On Error GoTo Catch
TryAgain:
Workbooks.Open "C:\Reports\Sales.xlsx"
Exit Sub
Catch:
attempts = attempts + 1
If attempts < 3 Then
Application.Wait Now + TimeValue("00:00:02")
Resume TryAgain
End If
MsgBox "Could not open the file after 3 tries.", vbCritical
End SubResume Next (skip and continue)
Resume Next continues at the line after the one that failed. It works as a statement on its own inside a handler, and as the argument in On Error Resume Next. The second form is the dangerous one, because from that line onward every error is swallowed. Wrap the single risky line and switch handling back on straight away:
Function SheetExists(sheetName As String) As Boolean
Dim ws As Worksheet
On Error Resume Next
Set ws = ThisWorkbook.Worksheets(sheetName)
On Error GoTo 0
SheetExists = Not ws Is Nothing
End FunctionThis is the one place where On Error Resume Next is the cleanest answer. The error is expected, the scope is one line, and the result is tested by the Nothing check.
On Error GoTo 0 (switch handling off)
On Error GoTo 0 disables the current handler. Errors after it behave as if you never wrote any handling, so Excel shows its dialog. It does not mean jump to line zero. Use it to close a Resume Next window, as in SheetExists above.
How does the Err object work in VBA?
Err is a built-in object that VBA fills in when an error occurs. You never declare it. The vba err object has a handful of members, and four of them cover most work.
| Member | Returns | Example value |
|---|---|---|
| Err.Number | Numeric error code | 11 |
| Err.Description | Text of the error | Division by zero |
| Err.Source | Name of the project or object that raised it | VBAProject |
| Erl (a function, not part of Err) | Line number, only if your code has line numbers | 40 |
| Err.Clear | Method that resets the object | sets Number to 0 |
| Err.Raise | Method that throws an error | see below |
Err.Number is 0 when no error is active. That makes this check useful after an On Error Resume Next line:
On Error Resume Next
Set wb = Workbooks.Open(path)
If Err.Number <> 0 Then
Debug.Print "Open failed: " & Err.Description
Err.Clear
End If
On Error GoTo 0How do you raise your own error with Err.Raise?
Err.Raise is the VBA throw. Use it when your validation fails and the calling procedure should decide what to do. Custom numbers should be vbObjectError plus a number so they do not clash with built-in codes.
Const ERR_BAD_QTY As Long = vbObjectError + 1001
Sub AddStock(qty As Long)
If qty <= 0 Then
Err.Raise ERR_BAD_QTY, "AddStock", "Quantity must be above zero."
End If
' ... update stock
End SubThe caller can then test For Err.Number = ERR_BAD_QTY and show a friendly message instead of a technical one.
What does a reusable VBA error handler template look like?
Copy this into any procedure that touches files, other workbooks or user input. It has a catch, a finally, a logged record and a friendly message. The only line you change is the procedure name.
Sub MyProcedure()
Const PROC_NAME As String = "MyProcedure"
On Error GoTo Catch
' ---- try ----
' your code here
Finally:
' ---- finally: always runs ----
Application.ScreenUpdating = True
Application.EnableEvents = True
Exit Sub
Catch:
LogError PROC_NAME, Err.Number, Err.Description
MsgBox "Something went wrong in " & PROC_NAME & "." & vbNewLine & _
"Details: " & Err.Description, vbExclamation, "Error " & Err.Number
Resume Finally
End Sub
Sub LogError(proc As String, num As Long, msg As String)
Dim f As Integer
f = FreeFile
Open ThisWorkbook.Path & "\error_log.txt" For Append As #f
Print #f, Format(Now, "yyyy-mm-dd hh:nn:ss") & " | " & proc & _
" | " & num & " | " & msg
Close #f
End SubThree details are worth knowing. First, LogError is a separate procedure, so a failure inside it will not loop back into the handler. Second, the log is a plain text file next to the workbook, so you can open it in Notepad. Third, it saves a copy of Err.Number and Err.Description before any other statement runs, because calling other code can overwrite the Err object.
Keep the handler short. A handler that does 30 things can fail itself, and an error inside a handler goes to the caller, not back to the same handler.
Worked example: import 12 monthly CSV files without crashing
Suppose a macro must import 12 monthly sales files named Sales_01.csv to Sales_12.csv from one folder. In a normal month all 12 exist. In a bad month two are missing, and without handling the macro stops at the first gap and leaves a half-built summary.
The goal is to import what exists, log what does not, and report the counts at the end.
Sub ImportMonthlyFiles()
Const PROC_NAME As String = "ImportMonthlyFiles"
Dim folder As String, path As String
Dim m As Long, okCount As Long, missCount As Long
Dim wb As Workbook
On Error GoTo Catch
Application.ScreenUpdating = False
folder = ThisWorkbook.Path & "\Sales\"
For m = 1 To 12
path = folder & "Sales_" & Format(m, "00") & ".csv"
If Dir(path) = "" Then
missCount = missCount + 1
LogError PROC_NAME, 53, "Missing file: " & path
Else
Set wb = Workbooks.Open(path)
wb.Worksheets(1).UsedRange.Copy _
Destination:=ThisWorkbook.Worksheets("Summary") _
.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)
wb.Close SaveChanges:=False
Set wb = Nothing
okCount = okCount + 1
End If
Next m
Finally:
Application.ScreenUpdating = True
MsgBox okCount & " imported, " & missCount & " missing.", vbInformation
Exit Sub
Catch:
LogError PROC_NAME, Err.Number, Err.Description
If Not wb Is Nothing Then wb.Close SaveChanges:=False
Resume Finally
End SubHere the expected problem (a missing file) is handled with an If test, because you can predict it. The unexpected problems (a locked file, a corrupt CSV, a protected sheet) go to the handler. With 2 files missing the user sees 10 imported, 2 missing, and the log holds the two paths.
That split is the main design rule: test for what you can foresee, trap what you cannot. Using an error handler to replace an If statement works but is slower to read and harder to debug.
Which VBA errors show up most, and how do you fix them?
Most run-time errors in Excel macros come from a short list. This table gives the code, the message and the usual cause.
| Error | Message | Typical cause | Fix |
|---|---|---|---|
| 5 | Invalid procedure call or argument | Bad argument, such as Mid with start 0 | Check the argument values with Debug.Print |
| 6 | Overflow | Integer variable above 32,767 | Declare the variable as Long |
| 9 | Subscript out of range | Sheet name or array index does not exist | Check the name or bounds before use |
| 11 | Division by zero | Divisor is 0 or an empty cell | Test the divisor with If before dividing |
| 13 | Type mismatch | Text in a cell where a number is expected, or an error value like #N/A | Use IsNumeric or IsError first |
| 53 | File not found | Wrong file name or path | Check with Dir before Open |
| 70 | Permission denied | File open elsewhere or read-only | Close the file or handle the error and retry |
| 76 | Path not found | Folder does not exist | Check the folder with Dir(path, vbDirectory) |
| 91 | Object variable or With block not set | Object used before Set, or a Find that returned Nothing | Test with Is Nothing |
| 424 | Object required | Wrong object reference or typo | Check names, use Option Explicit |
| 438 | Object doesn’t support this property or method | Property does not exist on that object | Check the object type in Locals |
| 1004 | Application-defined or object-defined error | Protected sheet, bad range, invalid sheet name | Read Err.Description, it carries the real reason |
Error 1004 is the catch-all of Excel VBA. The number alone tells you little, so always display Err.Description with it.
How do you debug VBA in Excel?
Error handling tells users something broke. Debugging tells you why. The VBA editor (press Alt+F11) has six tools that cover nearly everything, and they work together. If you are new to the editor, the Excel macros for beginners guide covers recording and running your first macros.
Stepping with F8
Click inside a procedure and press F8. VBA runs one line, highlights the next in yellow and waits. Pressing F8 repeatedly lets you watch the logic move. Shift+F8 steps over a called procedure, and Ctrl+Shift+F8 runs until the current procedure ends. This is the quickest way to find the line that fails.
Breakpoints with F9
Click in the grey margin or press F9 on a line to set a breakpoint, shown as a red dot. VBA runs at full speed until it reaches that line, then pauses. Use a breakpoint inside a loop to skip the first 500 passes and stop where it matters. Press F5 to continue and Ctrl+Shift+F9 to clear every breakpoint.
The Immediate window
Press Ctrl+G. In break mode you can type ? followed by an expression, such as ?Range(“B1”).Value, and press Enter to see the current value. You can also run statements, for example Range(“B1”).Value = 5. Debug.Print in your code writes to this window, which is how you trace values without showing message boxes.
The Locals window
Open it from View, Locals Window. It lists every variable in the running procedure with its current value and type. Expand an object, such as a Worksheet, and you can see its properties. It is the fastest way to catch an object that is Nothing or a variable that holds the wrong type.
The Watch window
Right-click a variable and choose Add Watch. You can watch a value, or set the watch to break when the value changes or becomes true. A condition such as total > 10000 stops the macro the moment it happens, which is far quicker than stepping through thousands of rows.
Call Stack, Compile and Debug.Assert
Ctrl+L opens the Call Stack, showing which procedure called which. That matters when an error appears in a helper that 6 other procedures use. Debug, Compile VBAProject checks the whole project for syntax problems before you run it. Debug.Assert condition pauses the code if the condition is False, which is useful for checks that should never fail.
| Tool | Shortcut | Best for |
|---|---|---|
| Step Into | F8 | Finding the exact failing line |
| Breakpoint | F9 | Skipping to a known trouble spot |
| Immediate window | Ctrl+G | Checking values and testing statements |
| Locals window | View menu | Seeing every variable at once |
| Watch window | Right-click, Add Watch | Stopping on a condition |
| Call Stack | Ctrl+L | Tracing which procedure called which |
| Run to Cursor | Ctrl+F8 | Running to a line without a breakpoint |
A short debugging routine that works
- Press Debug, Compile VBAProject and fix every syntax error.
- Run the macro. When the error dialog appears, click Debug to land on the yellow line.
- Open the Locals window and check each variable on that line.
- Use the Immediate window to test the suspect expression.
- Set a breakpoint a few lines earlier and step with F8 to see how the value got there.
- Fix the cause, then add a handler or an If test so the same failure is reported clearly next time.
How we put this guide together
The error numbers and messages above come from the standard VBA run-time error list and the On Error documentation from Microsoft. The code samples are written for desktop Excel on Windows (2016 to Microsoft 365), where the VBA editor and the Locals and Watch windows are available. Excel for the web and Excel on Mac do not give you the same editor. Every pattern uses plain VBA with no add-ins and no downloads.
What are the common VBA error handling mistakes?
| Mistake | What happens | Fix |
|---|---|---|
| No Exit Sub before the label | The handler runs after every successful run | Put Exit Sub or Exit Function above the label |
| On Error Resume Next at the top of a procedure | Every error is hidden and results are wrong without warning | Use it around one line, then On Error GoTo 0 |
| Resume with no fix | The same line fails forever and Excel hangs | Count attempts or change the cause first |
| Forgetting to restore settings | ScreenUpdating or Calculation stays off after a crash | Restore them in a Finally label |
| Reading Err after other code runs | Err.Number is already reset to 0 | Copy the number and description first |
| One generic message for everything | Users cannot report what went wrong | Show the procedure name and Err.Description |
| Handler errors inside the handler | Error goes to the caller, or Excel’s dialog | Keep the handler small and call a safe logger |
When is a VBA try catch the wrong answer?
Error handling is not a cure for every problem, and sometimes it is the wrong tool.
- The error is predictable. Division by zero, a missing file and an empty cell are better tested with If and Dir than trapped. A handler that fires on routine input is a design smell.
- The code is wrong, not the data. If a macro fails every time, you need the debugger, not a handler. Hiding a logic bug behind a message box makes it harder to find.
- You use Excel for the web, Mac or Google Sheets. The VBA editor and the debugging tools described here are for Excel on Windows. Google Sheets uses Apps Script, which does have try and catch.
- The work is a plain calculation. If a formula such as IFERROR solves it, a macro and a handler add maintenance with no benefit.
- The process needs many users or an audit trail. A shared, multi-user system with permissions is better served by a database or dedicated software than by a macro workbook with a text log.
Where can you see working Excel VBA applications?
Reading real macros teaches faster than reading tutorials. The templates below are finished VBA workbooks with UserForms, menus and reports. The Excel VBA Tools & Utilities Pack lists editable VBA source, so you can study how a project is organised and adapt it. We do not describe their internal error handling, so treat them as working examples of structure, forms and automation rather than a try catch reference.
The Excel VBA UserForm tutorial is a good companion if you want to build your own forms first, and our list of Excel VBA tools for small business shows what ready-made automations cover.
| Template | Format | Best for | Price |
|---|---|---|---|
| Excel VBA Tools & Utilities Pack (Best overall) | Excel VBA (Windows) | 8 VBA applications: inventory, orders, invoicing, hospital, leave, PDF conversion, Kanban | $63.99 |
| VBA Management Systems Mega Pack (Best value) | Excel VBA (Windows) | 5 systems: inventory, hospital, dental clinic, order, task management | $49.99 |
| Workbook Merger and Splitter Tool V1.0 | Excel VBA (Windows) | Merging a folder of Excel and CSV files, or splitting one workbook | $29.00 |
| Warehouse Receiving and Putaway System V1.0 | Excel VBA (Windows) | GRN entry, bin putaway and discrepancy logs | $29.00 |
| Loan and EMI Management System V1.0 | Excel VBA (Windows) | Loan books, EMI schedules and overdue tracking | $29.00 |
| Multi-Location Inventory and Billing Management System V1.0 | Excel VBA (Windows) | One warehouse and several stores in one file | $29.00 |
Excel VBA Tools & Utilities Pack, $63.99
This pack holds 8 Excel VBA applications: two inventory systems, an order system, an invoicing system, a hospital system, an HR leave tracker, a PDF-to-Excel converter and a Power Pivot Kanban board. Bought one by one they total $105.92, and the bundle is $63.99, a saving of $41.93. It runs on Excel 2016 to Microsoft 365 for Windows. See the Excel VBA Tools & Utilities Pack.
VBA Management Systems Mega Pack, $49.99
Five systems (inventory, hospital, dental clinic, order and task management) with login, UserForm data entry and PDF or Excel report export, for $49.99 instead of $99.95. It is the cheaper entry point if you want several full VBA projects to open and read. Get the VBA Management Systems Mega Pack.
Single-purpose VBA tools, $29.00 each
If you need one job done, the Workbook Merger and Splitter Tool merges a folder of Excel and CSV files into one workbook or splits one into many without changing the source files, which is the same file-handling problem as the import example above. The Warehouse Receiving and Putaway System and the Loan and EMI Management System are both $29.00 and come with sample data. Each has a 7-day free trial, so you can test it on your own PC first. You can also read about the Workbook Merger and Splitter Tool in Excel VBA, the Warehouse Receiving and Putaway System in Excel VBA and the Loan Management System in Excel VBA with EMI Schedule in their own posts.
For form inputs that stop bad data before it reaches your code, see Excel drop down list data validation. Validation prevents many of the errors in the table above.
How do you choose which error handling pattern to use?
| Situation | Pattern |
|---|---|
| One line may fail and you expect it | On Error Resume Next, check Err, then On Error GoTo 0 |
| A whole procedure touches files or other workbooks | On Error GoTo Catch with a Finally label |
| The failure can be fixed and retried | Resume with an attempt counter |
| Your own input check fails | Err.Raise with a custom number |
| A macro fails every time | No handler, use F8, Locals and the Immediate window |
Frequently asked questions
Does VBA have try catch?
No. VBA has no Try, Catch or Finally keywords. The equivalent is On Error GoTo with a label: the code above the label is the try, the label is the catch, and a second label reached with Resume acts as finally. It works in every desktop version of Excel.
What is the difference between Resume and Resume Next in VBA?
Resume re-runs the line that caused the error, so use it only after fixing the cause. Resume Next skips that line and continues with the next one. Resume Label jumps to a named line, which is how you reach a cleanup section after an error.
What does On Error GoTo 0 do?
On Error GoTo 0 turns off error handling for the current procedure. After it, a run-time error shows Excel’s standard dialog again. It does not jump to line zero. Place it right after a risky On Error Resume Next line so later errors are not hidden.
How do I show the error message in VBA?
Inside your handler, use MsgBox with Err.Number and Err.Description, for example MsgBox “Error ” & Err.Number & “: ” & Err.Description. Add the procedure name so users can tell you where it happened. For long jobs, write the same text to a log file as well.
What is the Err object in VBA?
The Err object is a built-in object that stores details of the latest run-time error. Its main members are Number, Description and Source, plus the Clear and Raise methods. Err.Number is 0 when no error is active, and any Resume statement or Err.Clear resets it.
How do I stop a VBA error from crashing my macro?
Start the procedure with On Error GoTo Catch and write a handler under an Exit Sub line. The handler can show a message, log the problem and exit cleanly. For one expected failure, wrap just that line in On Error Resume Next and test Err.Number afterwards.
How do I debug VBA code in Excel?
Open the editor with Alt+F11, click in the procedure and press F8 to step one line at a time. Set breakpoints with F9, check values in the Immediate window with Ctrl+G, and inspect variables in the Locals and Watch windows. Debug, Compile VBAProject finds syntax errors first.
What does Run-time error 1004 mean in Excel VBA?
Error 1004 is Application-defined or object-defined error, a general Excel failure. Common causes are a protected sheet, a range that does not exist, an invalid sheet name or a file that cannot be saved. Read Err.Description, because it holds the specific reason behind the number.
How do I raise a custom error in VBA?
Use Err.Raise with a number, a source and a description, for example Err.Raise vbObjectError + 1001, “AddStock”, “Quantity must be above zero.” Adding vbObjectError keeps your codes apart from built-in ones. The calling procedure catches it with its own handler.
Why does my VBA error handler run even when there is no error?
The code reached the label by running straight down the page. Add Exit Sub (or Exit Function) on the line above the label so the success path leaves before the handler. If you use a Finally label, put Exit Sub at the end of that section instead.
Get more Excel VBA templates
If you want finished VBA projects to study and use, the Excel VBA Tools & Utilities Pack gives you 8 applications for $63.99, against $105.92 bought separately. The VBA Management Systems Mega Pack has 5 systems for $49.99. Single tools are $29.00 each, and the same range is covered in our inventory management templates in Excel and VBA roundup. Video walkthroughs are on the Next Gen Templates YouTube channel.



