The "Runtime Error 9: Subscript Out of Range" in Excel VBA occurs when you try to reference a cell, worksheet, or array index that doesn’t exist in the range you’re working with. This error is one of the most frequent issues macro writers face but is almost always fixable with minor adjustments. To resolve it, you need to verify your array references, conditional loops, or dynamic ranges align correctly with what actually exists in your workbook.
What You'll Need
- A copy of Microsoft Excel (2007 or later)
- Access to the VBA editor (press Alt + F11 to open it)
- An Excel workbook with your macro or code (or a test workbook if creating new code)
- Common sense and patience to debug
Step-by-Step
-
Start with a clean test case:
Open a fresh Excel workbook and create minimal code that reproduces the error. Replace your macro with this simple test:
Sub TestSubscript() Dim ws As Worksheet Set ws = ThisWorkbook.Worksheets("Sheet1") MsgBox "Sheet1 exists." & vbCrLf & "Test passed." End SubRun it. If it works, the error is likely tied to a specific worksheet, range, or variable reference. -
Check array dimensions:
If your error occurs when looping through ranges or arrays, verify that the loop bounds match the actual data:
Sub LoopThroughExample() Dim i As Integer Dim lastRow As Long lastRow = Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row For i = 1 To lastRow ' Your code here Next i End SubThe error often happens when you use `Rows.Count` or `Columns.Count` without accounting for blank cells. -
Validate worksheet names:
Always check if the worksheet exists before referencing it:
Sub SafeWorksheetAccess() On Error Resume Next Dim ws As Worksheet Set ws = ThisWorkbook.Worksheets("Sheet2") On Error GoTo 0 If ws Is Nothing Then MsgBox "Worksheet 'Sheet2' does not exist." Exit Sub End If ' Continue with code End SubUse theOn Error Resume Nexttechnique to catch errors early. -
Inspect cell references:
The error often appears when referencing a cell that doesn’t exist. Replace hardcoded cells with variables or dynamic references:
Sub SafeCellReference() Dim cell As Range Set cell = Worksheets("Sheet1").Range("A1:A100") ' Leave blank cells in A1:A100 ' Your code here End SubNever assume a cell exists at a fixed position. -
Check for typos:
The most common culprit is a misspelled worksheet name or range. For example:
Worksheets("Sheet One")(with a space) won’t work in VBA; useWorksheets("Sheet1")instead. -
Debug with immediate window:
Add this to your code to log variables:
Sub DebugVariables() Debug.Print "Worksheet name: " & ActiveSheet.Name Debug.Print "Last row: " & Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row ' Your code End SubPress F8 to step through the code and check values in the Immediate Window (Ctrl+G).
Common Mistakes
- Assuming worksheet names match: Excel worksheet names are case-sensitive and can’t contain spaces or special characters. Always verify the exact name. Example: If your worksheet is named "Team Meetings," VBA will fail if you use "TeamMeetings."
-
Using fixed ranges in loops:
Hardcoding ranges like
Range("A1:A50")can cause issues if the data is larger or smaller. Use dynamic ranges instead. - Ignoring error handling: Skipping checks for worksheet existence or cell availability leads to runtime errors.
- Copy-pasting code without testing: Copying macros from other sources often introduces typos or range mismatches.
Tips
-
Use conditional logic:
Always wrap worksheet/reference checks in error handling:
On Error Resume Next Set ws = Worksheets("SheetX") On Error GoTo 0 If Err.Number <> 0 Then Exit Sub - Prefer dynamic ranges: Always use `Cells(Rows.Count, 1).End(xlUp).Row` instead of fixed row numbers.
- Test with small datasets: Start with a single row or column to isolate the issue.
-
Check for hidden worksheets:
Hidden worksheets won’t appear in `Worksheets.Count`. Use:
Worksheets("SheetX").Visible = xlSheetVisibleto ensure they’re visible. -
Use `Option Explicit`:
Enable strict variable checking by adding this at the top of your module:
Option Explicit
This catches undeclared variables early.
Troubleshooting
- If the error persists after basic checks: Recreate the exact code snippet in a new workbook. Sometimes old references (like `Worksheets("Sheet1")` left over from previous code) cause issues.
- Check for circular references: If you’re using loops or arrays, ensure no ranges reference themselves unintentionally. If the error occurs in a loop: Sometimes the last iteration fails. Add a `Stop` command inside the loop to manually check values:
- If the issue is with a third-party add-in: Disable add-ins one by one to identify if the error originates from an external module.
For i = 1 To lastRow
If Cells(i, 1).Value = "" Then Stop 'Debug here
Next i
Common Causes of "Subscript Out of Range"
The error generally occurs in these scenarios:
- Referencing a worksheet that doesn’t exist in the workbook.
- Using an array index that exceeds the actual data range (e.g., `Range("A1:A100")` with only 5 rows of data).
- Assuming a cell always exists at a fixed position (e.g., `Range("A1").Value`).
- Looping through a range where the last row is empty or doesn’t match expectations.
Frequently Asked Questions
Why does my macro crash when it should work?
Most likely, your macro is referencing a worksheet, cell, or array index that doesn’t exist in the current workbook. Verify the exact name, range, and data size before execution.
How do I fix an error when referencing "Sheet1" in VBA?
Use this defensive approach: On Error Resume Next; Set ws = Worksheets("Sheet1"); On Error GoTo 0. If "Sheet1" doesn’t exist, the macro will continue without crashing.
What should I do if I copied a macro from another source?
Always rewrite or test the macro in your own workbook. Copy-pasting code often introduces typos (like misspelled worksheet names or incorrect ranges) that can cause "subscript out of range" errors.
Why does this error happen when looping through rows?
The most common cause is using Rows.Count without accounting for blank cells. Replace it with Cells(Rows.Count, 1).End(xlUp).Row to dynamically find the last populated row.
How do I debug a VBA macro without seeing the error message?
Use the Immediate Window (Ctrl+G) to print variable values. Add Debug.Print variableName to your code and run it step-by-step with F8.
What if my macro works on one workbook but not another?
The issue is likely due to differences in worksheet names, data ranges, or hidden sheets. Test the macro in the target workbook and adjust references accordingly.