top of page

VBA: ErrObject — Parts, All Error Types, Why They Occur and How to Fix Them

  • Writer: Fakhriddinbek
    Fakhriddinbek
  • Oct 5
  • 6 min read

Updated: Oct 8

Errors are inevitable when you automate Excel with VBA. What separates robust projects from fragile macros is how you detect, handle, and recover from those errors. This post explains the VBA ErrObject, its parts (properties and methods), all broad error types in VBA, common runtime error numbers, step-by-step handling patterns, practical examples, and how AI can help you debug — all written to be clear and practical.


VBA editor in Excel displays a code module with an open "Object Browser." "Object" is selected under "View." The environment is technical.
Exploring the Visual Basic for Applications (VBA) interface in Microsoft Excel, the image illustrates the use of the Object Browser to examine the 'ErrObject' properties during coding for error logging in Excel macros.

What is the ErrObject?

Err (the ErrObject) is a built-in VBA object that stores information about runtime errors. When a runtime error occurs, VBA fills Err with diagnostic data you can read or modify. Err is essential to robust error handling, logging, and user-friendly messages.


Main parts (properties & methods)

  • Err.Number — numeric error code (e.g., 9, 1004, 13).

  • Err.Description — human-readable message (depends on environment/language).

  • Err.Source — string naming the object or procedure that raised the error.

  • Err.HelpFile — path to a help file (rarely used).

  • Err.HelpContext — numeric help topic ID.

  • Err.LastDllError — last error from external DLL calls (useful for API/Win32 calls).

  • Err.Raise(number, source, description, helpfile, helpcontext) — raise a custom error.

  • Err.Clear — clear the Err object (sets Number = 0 and clears text).


How many VBA error types exist? (high level)

Broadly VBA errors fall into three categories:


  1. Compile-time errors (Syntax / Declaration)

    • Detected before code runs. Examples: missing End If, invalid variable declarations, mismatched quotes. Fix by correcting syntax or references.


  2. Run-time errors (Runtime)

    • Occur while code runs. ErrObject applies here. Examples: file not found, object not set, subscript out of range, division by zero.


  3. Logic errors (Semantic / Business logic)

    • Code runs without exceptions but produces wrong results — the hardest to detect. Use unit testing, assertions, and thorough logging.


In addition, there are host/automation errors (integration with Excel, Word, COM objects) and API/DLL errors (LastDllError) — these are subtypes of runtime errors but are worth separate attention.


Common runtime error numbers (most frequently seen in Excel VBA)

Below is a compact list of common runtime errors you'll encounter, with short fixes.


Visual Basic editor shows “Subscript out of range” error in a pop-up. Code window highlights error-prone line. Gray interface with text.
VBA error encountered: The code in the "Example_Error9_WrongSheetName" subroutine results in a "Run-time error '9': Subscript out of range" due to an attempt to reference a non-existent sheet named "Data_Sheet". The Object Browser highlights the 'ErrObject' class, showing its members.

  • 9 — Subscript out of range

    Cause: Worksheet/Workbook index/name doesn't exist.Fix: Verify sheet/workbook names, use If SheetExists(...) Then.


    Example:

    Sub Example_Error9_WrongSheetName()

    Dim ws As Worksheet

    ' This line throws "Subscript out of range" if the sheet doesn't exist

    Set ws = ThisWorkbook.Sheets("Data_Sheet")

    ws.Range("A1").Value = "Hello World"

    End Sub


    Solution:

    Sub Example_Fix_Error9_SheetCheck()

    Dim ws As Worksheet

    Dim sheetName As String

    sheetName = "Data_Sheet"

    ' Check if sheet exists before setting object

    If SheetExists(sheetName) Then

    Set ws = ThisWorkbook.Sheets(sheetName)

    ws.Range("A1").Value = "Hello World"

    Else

    MsgBox "Sheet '" & sheetName & "' not found! Creating it now...", vbInformation

    Set ws = ThisWorkbook.Sheets.Add

    ws.Name = sheetName

    ws.Range("A1").Value = "New Sheet Created"

    End If

    End Sub


    ' Helper function to check sheet existence

    Function SheetExists(sName As String) As Boolean

    Dim ws As Worksheet

    On Error Resume Next

    Set ws = ThisWorkbook.Sheets(sName)

    SheetExists = Not ws Is Nothing

    On Error GoTo 0

    End Function


  • 13 — Type mismatch

    Cause: Assigning incompatible types (String → Long etc.).

    Fix: Use CInt, CLng, validate input with IsNumeric, or use Variant.


  • 91 — Object variable or With block not set

    Cause: Using an object variable that is Nothing.

    Fix: Set obj = ... before use; check If obj Is Nothing Then.


  • 424 — Object required

    Cause: Missing Set, or wrong object reference.

    Fix: Ensure correct object creation and Set for object assignment.


  • 1004 — Application-defined or object-defined error (Excel specific)

    Cause: Range/worksheet operations fail (e.g., invalid range, protected sheet).

    Fix: Validate ranges, unprotect sheets, fully qualify references: ThisWorkbook.Worksheets("Sheet1").Range("A1").


  • 53 — File not found

    Cause: File path wrong or missing.Fix: Use Dir to check existence; provide absolute paths.


  • 70 — Permission denied

    Cause: File locked, insufficient rights.

    Fix: Close file elsewhere, check permissions, handle read/write modes.


  • 11 — Division by zero

    Fix: Check denominator before dividing. Overflow

    Cause: Value too big for variable type.

    Fix: Use larger type (Long → Double) or validate ranges.


  • 438 — Object doesn’t support this property or method

    Cause: Calling wrong method on object.

    Fix: Check object type and method availability.


This is not exhaustive — VBA has dozens more error codes — but these are the most actionable.


Step-by-step guide: robust error handling pattern

Use this step-by-step approach whenever you build or refactor VBA code.


1) Identify & reproduce

  • Run the macro, note the exact error number and description.

  • Reproduce with minimal input — create a small workbook/code sample that triggers the error.


2) Localize the failing line

  • Use F8 (step into) in the VBA IDE or add Debug.Print statements before suspected operations.

  • Example: if copy/paste fails, determine whether .Range, .Copy, or .Paste raised the error.


3) Add an error handler

Use a standard handler at the start of routines.

Sub Example()
    On Error GoTo ErrHandler
    ' --- your code here ---
    Exit Sub
ErrHandler:
    Debug.Print "Error " & Err.Number & " in Example: " & Err.Description
    ' optional: write log or show message
    Resume Next ' or Exit Sub or Resume
End Sub

4) Log and recover

  • Create an error log sheet or write to a text file with Date, Procedure, Err.Number, Err.Description, and stack info.

  • Clean up objects (release references), restore application settings (ScreenUpdating, EnableEvents).


5) Rethrow or wrap

  • For library code, use Err.Raise to rethrow with additional context so caller can handle:

If somethingWrong Then
    Err.Raise 1001, "MyModule.MyProcedure", "Validation failed for parameter X"
End If

6) Fix root cause

  • After logging and isolating, correct code — fix invalid names, validate inputs, guard against Nothing, etc.


Practical examples (real-life cases)

A. Subscript out of range (error 9)

Sub OpenSheet()
    On Error GoTo EH
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Worksheets("Data") ' error if "Data" missing
    ws.Range("A1").Value = "OK"
    Exit Sub
EH:
    MsgBox "Could not find worksheet 'Data'. Error " & Err.Number
    ' Optional: create sheet programmatically:
    ThisWorkbook.Worksheets.Add(After:=ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count)).Name = "Data"
    Resume Next
End Sub

B. File not found (error 53) — safe file open

Sub OpenFileSafe(filepath As String)
    On Error GoTo EH
    If Dir(filepath) = "" Then
        Err.Raise 53, "OpenFileSafe", "File not found: " & filepath
    End If
    ' open file code...
    Exit Sub
EH:
    Debug.Print Err.Number & ": " & Err.Description
    ' Provide fallback or user prompt
End Sub

C. Logging errors to an ErrorLog sheet

Sub LogErrorToSheet(procedureName As String)
    Dim sht As Worksheet
    On Error Resume Next
    Set sht = ThisWorkbook.Worksheets("ErrorLog")
    If sht Is Nothing Then
        Set sht = ThisWorkbook.Worksheets.Add
        sht.Name = "ErrorLog"
        sht.Range("A1:E1").Value = Array("Time","Procedure","Error","Description","Source")
    End If
    On Error GoTo 0
    sht.Cells(sht.Rows.Count, "A").End(xlUp).Offset(1).Value = Array(Now, procedureName, Err.Number, Err.Description, Err.Source)
End Sub

Best practices & tips (quick)

  • Always qualify workbook/sheet/range references.

  • Prefer On Error GoTo ErrHandler over On Error Resume Next (which easily hides bugs).

  • Use specific checks (If obj Is Nothing Then) rather than letting runtime errors happen.

  • Clear Err with Err.Clear after handling.

  • Include cleanup code (Close files, set objects Nothing) in your handler or a Finally style section.

  • Use meaningful error numbers when raising custom errors (above 512 reserved for user-defined).


Possible AI usage for this topic + which AI suits best

AI can help by:

  • Explaining errors (give error number + code and ask for explanation).

  • Suggesting fixes from minimal reproducible examples.

  • Refactoring error handling to modern patterns.

  • Writing tests / synthetic data that reproduce edge cases.


Which AI to use:

  • For code generation and debugging: code-aware models (GitHub Copilot, Codex-like assistants, or GPT-4/GPT-4o with code capabilities).

  • For deeper step-by-step reasoning and explanation: large language models that handle code context well (GPT-4 family).

  • For quick inline suggestions inside editors: Copilot / TabNine.


Prompt template for best results (paste to any AI assistant):

I have this VBA sub (paste code). When I run it in Excel 2016 I get "Error 1004: Application-defined or object-defined error" at line X. Expected behavior: ... Steps to reproduce: ... Please explain why, show minimal fix, and provide a robust error handler to add.

FAQ — top 7 trending questions

  1. Q: When should I use On Error Resume Next?A: Only for very small, well-scoped statements where you immediately test Err.Number. Avoid globally—it's a common source of hidden bugs.

  2. Q: How do I log errors centrally?A: Create an ErrorLog worksheet or text file and write Now, Procedure, Err.Number, Err.Description, Err.Source. Call a LogError sub from your handlers.

  3. Q: What’s the difference between Err.Raise and Err.Clear?A: Err.Raise creates a new runtime error (useful to signal validation failures). Err.Clear resets Err after handling.

  4. Q: How do I debug 1004 Application-defined errors?A: Check fully qualified range references, sheet protection, merged cells, and workbook focus. Step through code to identify the exact failing method.

  5. Q: Can I get a stack trace in VBA?A: Not natively. You can add a ProcedureName parameter to functions and include it in Err.Raise/logs to simulate a stack trace.

  6. Q: How to fix Type mismatch?A: Validate inputs with IsNumeric, cast using CInt/CLng/CStr, and declare variables with the correct types. Use Variant for mixed content.

  7. Q: Should I show raw Err.Description to users?A: Prefer friendly messages. Log detailed Err info for diagnostics, and show the user a simple prompt with steps (e.g., “Close other workbooks and try again”).


If you want, send one of your problematic macros (minimal reproducible example) and the exact error message — I’ll analyze it, give a fixed version, and add a robust error-handling wrapper + a logging sub you can paste into any workbook. Also follow for more Excel VBA tutorials and ready-to-use error-handling templates.

Comments


bottom of page