An implementation of Visual Basic that is built into Microsoft products.
Run-time error 9: Subscript out of range in Excel VBA means the code is trying to access something that does not exist at that index or name.
Common causes in VBA:
- Array index is outside the valid range
- The subscript is smaller or larger than the allowed bounds.
- Check the array declaration.
- Use
LBoundandUBoundbefore accessing elements. - If the array was declared without a size, it must be dimensioned first with
DimorReDim.
Dim MyArray() As Integer MyArray(8) = 234 - A collection or workbook/sheet item does not exist
- This happens when code refers to a nonexistent member, such as an invalid collection key or an object that is not open or not present.
- A similar example is trying to access
Workbooks(5)when only three workbooks are open. - If looping through a collection,
For Each...Nextcan be safer than hard-coded indexes.
- A sheet, macro, or object name is misspelled
- Check spelling carefully, especially if the index or name is stored in a variable.
- If code uses names with special or Unicode characters, that can also cause this issue in some environments.
- The code expects an array, but the variable is not an array in scope
- Verify the variable name is correct.
- Misspelling can create a different variable instead of using the intended array.
For Visual Basic arrays generally, the lowest subscript is 0, and the highest valid subscript is returned by GetUpperBound.
A practical way to fix it in the VBA editor:
- Open the VBA editor with
Alt+F11. - Run the macro again.
- When the error appears, click Debug.
- Check the highlighted line and verify:
- array index is within
LBoundandUBound - workbook, worksheet, or collection item exists
- object names are spelled exactly correctly
- arrays were dimensioned before use
- array index is within
- If the code refers to sheet names or macro names containing special characters, test by renaming them to simple ASCII names.
If the failing line is shared, the exact cause can usually be identified from that one statement.