The error **"VBA Runtime Error 91: Object variable or With block variable not set"** in Excel macros means your code is trying to reference a variable or object that isn’t defined yet—likely because a looping structure (like `For Each`, `Do While`, or a `With` block) runs before the object exists. This is the most common VBA mistake and can freeze your macro. The fix is straightforward: ensure every variable used in loops or nested operations has an initial assignment or proper initialization. The quickest solution is to check your `For Each` loops (which require an array or collection) or the `With` block (which must reference an existing object).
What You'll Need
- A working Excel workbook (macros enabled).
- VBA editor access (press
Alt+F11to open it). - Basic knowledge of Excel sheets, ranges, and simple loops (optional but helpful).
Step-by-Step Fix
-
Identify the error line:
Open your macro editor (Excel > Alt+F11). Press
F8to set breakpoints, then run your macro step-by-step. PressF9to execute one line, or use the "Step Into" button in the debugger toolbar. When you hit error 91, note the line number and line text. The error often points to a missing variable or object. If that doesn’t work: Look for `For Each` loops or `With` statements in your code—these are the most common culprits. -
Check `For Each` loops:
If your code contains a `For Each` loop (e.g., `For Each cell In Range`), ensure the `Range` variable is defined before the loop. For example:
For Each cell In Sheets("Sheet1").Range("A1:A10")is valid, but this will fail if `Sheets("Sheet1")` doesn’t exist. Add a check:If Sheets("Sheet1").Exists Then For Each cell In Sheets("Sheet1").Range("A1:A10") ... End IfAlternative: Assign the range to a variable first:Dim myRange As Range: Set myRange = Sheets("Sheet1").Range("A1:A10")
For Each cell In myRange ... End For -
Fix `With` blocks:
If you’re using a `With` block (e.g., `With Sheets("Sheet1").Range("A1")`), ensure the object (e.g., `Sheets("Sheet1")`) is valid before entering the block. Example:
If Not Sheets("Sheet1").IsNothing Then With Sheets("Sheet1").Range("A1") ... End WithIf the object isn’t needed: Remove the `With` block entirely. -
Initialize variables:
If the error occurs when referencing a variable like `myObject` or `mySheet`, declare it before use:
Dim mySheet As Worksheet: Set mySheet = Sheets("Sheet1")For collections/arrays: Ensure arrays are pre-populated:
If mySheet Is Nothing Then MsgBox "Sheet not found!"
Else ...Dim myData() As Variant: myData = Array(1, 2, 3)
For i = LBound(myData) To UBound(myData) ... -
Debug with Is Nothing checks:
Add safety checks around objects. For example:
If Not Intersect(ActiveSheet, Sheets("Sheet1")) Is Nothing Then ...wraps a sheet check to avoid errors if the sheet isn’t active.
Common Mistakes
- Looping before initialization: Writing a `For Each` loop over a variable that hasn’t been assigned yet (e.g., `For Each cell In Sheets("NonExistent")`).
- Using `With` on undefined objects: For example, `With ActiveSheet.Range("A1")` if `ActiveSheet` isn’t set or the sheet isn’t open.
- Overlooking `Set` statements: Forgetting to use `Set` when assigning objects (e.g., `Dim ws As Worksheet` without `Set ws = Sheets("Sheet1")`).
- Dynamic sheet references in loops: Assuming `Sheets("Sheet1")` will always exist—add existence checks.
Tips
- Use
Option Explicitat the top of your VBA module to catch undeclared variables early (enable this in the editor’s Tools > Options menu). - Replace `For Each` loops with explicit loops when possible for clarity:
For i = 1 To 10
Dim cell As Range: Set cell = Sheets("Sheet1").Cells(i, 1)
... - Use `On Error Resume Next` sparingly—it masks errors but isn’t a fix. Prefer explicit checks.
- For large datasets, pre-load data into arrays or collections before looping to avoid runtime errors.
Troubleshooting
- Restart Excel and the macro: Sometimes, the VBA environment gets sluggish. Close all Excel instances, restart your PC, and reopen Excel with macros enabled.
-
Update Excel: Run
File > Options > Add-ins > Manage Microsoft Excel Add-ins > Update allto ensure you’re using the latest VBA compatibility code. - Check for typos: In the error message, look for partial matches (e.g., `Sheets` vs. `Sheets1`). Run a search in your VBA editor (Ctrl+F) for the problematic variable name.
- Test in a clean workbook: Open a new Excel file, copy your macro, and run it. If the error persists, the issue is in your code logic, not Excel.
- Reinstall VBA editor: If the error keeps appearing, uninstall and reinstall the VBA editor (Excel’s built-in module). Avoid third-party editors unless necessary.
Frequently Asked Questions
Why does my `For Each` loop fail with error 91?
Your loop references a variable (e.g., `Sheets("Sheet1")`) that isn’t defined. Add a check like `If Sheets("Sheet1").Exists Then ...` or assign the range to a variable first.
How do I fix a `With` block error?
Ensure the object being referenced exists. Replace `With ActiveSheet.Range("A1")` with `If Not ActiveSheet Is Nothing Then With ActiveSheet.Range("A1") ...`.
Can I use `Option Explicit` to prevent error 91?
Yes! Enable it in Tools > Options > Editor Options > General. It forces you to declare all variables, catching undeclared references early.
What if the error still happens after fixing the code?
Check for conflicting macros or corrupted Excel files. Open a new workbook, paste your code, and test. If the error persists, inspect third-party add-ins (disable them via Add-ins > Manage COM Add-ins to rule them out).
How do I debug a VBA loop without line-by-line stepping?
Use the Debug.Print statement to log variable values where you expect them to be defined, then check the Immediate Window (Ctrl+G in the editor).
Is there a way to auto-fix missing variables?
No built-in tool exists, but ReSharper or similar code editors can suggest fixes for undeclared references. For free, use the debugger’s Watch window to check variable states.