Excel VBA Subscript Out of Range: Causes and Fixes
In this article
The "Subscript out of range" error (Run-time error '9') occurs when your VBA code attempts to access an element of a collection or an array that does not exist. This most commonly happens when you reference a worksheet name that is misspelled, a workbook that isn't open, or an array index that exceeds the defined upper or lower bounds of that array. To fix it, you must ensure the index number or name you are calling matches exactly what is available in the Excel environment at the moment the code executes.
What You'll Need
- Microsoft Excel with the Developer tab enabled.
- An existing VBA project or module where the error is occurring.
- The Visual Basic Editor (VBE), accessed via Alt + F11.
- The specific workbook and worksheets your code is designed to manipulate.
Step-by-Step
- Trigger the Error to Locate the Line: Run your macro. When the "Run-time error '9': Subscript out of range" dialog box appears, click the Debug button. This will highlight the specific line of code causing the crash in yellow.
- Identify the Target Object: Look at the highlighted line. Determine if the code is trying to access a Worksheet, a Workbook, or an Array. For example,
Sheets("Data").Selecttargets a worksheet, whilemyArray(10) = "Test"targets an array. - Verify Worksheet and Workbook Names: If the error is on a line referencing a sheet or book, check the spelling. VBA is literal. If your sheet is named "Sales " (with a trailing space) but your code says
Sheets("Sales"), you will get a subscript out of range error. Check for hidden characters, leading spaces, or typos in the tab name. - Confirm Workbook Status: If you are referencing another workbook using
Workbooks("Report.xlsx"), that file must be open in the current instance of Excel. If the file is closed, VBA cannot find it in the collection of open workbooks, triggering the error. Open the file manually or addWorkbooks.Open("C:\path\to\file.xlsx")to your code before the reference. - Check Array Bounds: If the error is occurring with an array, hover your mouse over the array variable and the index variable (e.g., the
iinmyArray(i)) while in Debug mode. This will show you the current value of the index. If the array was dimmed asDim myArray(1 To 5)and the indexiis currently 6, the code is trying to access a slot that doesn't exist. - Inspect Dynamic Array Redimensions: If you are using a dynamic array, check where
ReDimis called. If you useReDim Preserveinside a loop, ensure the size is increasing correctly and that you aren't accidentally resetting the array to a size smaller than the current index you are trying to access. - Verify Option Base Settings: Check the very top of your module for
Option Base 0orOption Base 1. If neither is present, VBA defaults to 0. If you assume an array starts at 1 but the system is using 0, you may encounter an error when accessing the final element or the first element depending on how the loop is structured. - Test with Index Numbers: If naming a sheet fails, try referencing it by its index number, such as
Sheets(1).Select. If this works, the problem is definitely the name string. If it still fails, the workbook may have fewer sheets than the index number you provided.
Common Mistakes
One of the most frequent mistakes is ignoring the difference between the "Code Name" and the "Sheet Name." In the VBA Project Explorer, you will see something like Sheet1 (SalesData). Sheet1 is the Code Name (which doesn't change even if the user renames the tab), while SalesData is the Sheet Name. If you use Sheets("Sheet1"), VBA looks for a tab actually named "Sheet1." If the tab was renamed to "SalesData," the code fails. Using the Code Name Sheet1.Select directly avoids this error entirely.
Another common error is failing to account for the 0-based nature of arrays. Many programmers coming from other languages assume arrays start at 1. In VBA, unless Option Base 1 is declared, Dim myArray(5) creates 6 elements (0 through 5). Attempting to access myArray(6) will immediately trigger the subscript out of range error.
Developers also frequently forget that Workbooks("FileName") requires the file extension. Writing Workbooks("Budget") instead of Workbooks("Budget.xlsx") will result in a subscript error because the collection cannot find a match for the exact string provided.
Tips
To prevent these errors, use variables for your sheet and book names. Instead of hard-coding Sheets("Monthly_Report_2023") multiple times, assign it to a variable at the start: Set ws = ThisWorkbook.Sheets("Monthly_Report_2023"). If the name changes, you only have to update it in one place.
When working with arrays, always use the LBound and UBound functions. Instead of writing For i = 1 To 10, write For i = LBound(myArray) To UBound(myArray). This ensures that your loop always stays within the actual boundaries of the array, regardless of how it was dimensioned or if the size changed during execution.
For more robust code, use a custom function to check if a worksheet exists before trying to access it. By looping through the ThisWorkbook.Sheets collection and comparing names, you can provide a user-friendly message like "The required sheet was not found" rather than letting the program crash with a technical Run-time error 9.
Troubleshooting
If you have checked the names and bounds and the error persists, try the following steps in order:
First, clear all compiled code. Sometimes the VBA compiler holds onto old references. Go to the Debug menu in the VBE and select Compile VBAProject. This will force the editor to check for syntax errors and refresh the project state.
Second, check for hidden sheets. While Sheets("Name") should find a hidden sheet, certain types of "Very Hidden" sheets (set via the properties window) can occasionally cause issues if you are using specific collection methods. Ensure the sheet is visible to verify its name and existence.
Third, verify the active workbook. If your code uses ActiveWorkbook or simply Sheets("Name") without a qualifier, it targets whatever window is currently in focus. If the user clicked on another open Excel file while the macro was running, the code will look for the sheet in the wrong workbook. Always qualify your references using ThisWorkbook.Sheets("Name") to ensure the code looks inside the file where the macro is stored.
Finally, if you are using an array that is populated from a range of cells, ensure the range isn't empty. If you assign a range to a variant array (e.g., myArray = Range("A1:B10").Value), VBA creates a 2D array. If you try to access it as a 1D array (e.g., myArray(1) instead of myArray(1, 1)), you will trigger a subscript out of range error because the second dimension is missing.
Frequently Asked Questions
Why does this happen even though the sheet name looks correct?
The most common cause is a leading or trailing space in the worksheet tab name that is invisible to the eye. Check the tab name in Excel and delete any spaces at the end of the text.
Does the error happen if the workbook is open in a different Excel instance?
Yes. If you have two separate windows of Excel open (two different processes), a macro in one instance cannot see the workbooks open in the other instance using the Workbooks() collection.
Can I ignore this error using On Error Resume Next?
You can, but it is dangerous. Using On Error Resume Next will simply skip the line and continue. If that line was supposed to set a variable or select a sheet, all subsequent lines of code will likely fail or operate on the wrong data.
What is the difference between LBound and UBound?
LBound returns the smallest available subscript for the array (usually 0 or 1), and UBound returns the largest available subscript. Using both in a loop prevents subscript errors.
Is this error related to memory or RAM?
No. "Subscript out of range" is a logic error, not a hardware resource error. It means you asked for a specific index number that the program has not allocated or cannot find.
How do I fix this when using a dynamic array?
Ensure you have used the ReDim statement to allocate space before assigning values. If you are adding items dynamically, use ReDim Preserve myArray(UBound(myArray) + 1) to expand the array without losing existing data.