Subscript out of range is an error we encounter in VBA when we try to reference something or a variable that does not exist in a code. For example, suppose we do not have a variable named x. Then, if we use the MsgBox function on x, we will encounter a “Subscript out of range” error.
VBA “Subscript out of range” error occurs because the object we are trying to access does not exist. It is an error type in VBA codingVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more, a “Run Time Error 9.” It is important to understand the concepts to write efficient code. It is even more important to understand the error of your VBA codeVBA error handling refers to troubleshooting various kinds of errors encountered while working with VBA. read more to debug the code efficiently.
If you make a coding error and do not know what that error is when you are gone.
A doctor cannot give medicine to his patient without knowing what the disease is. Doctors and patients both know there is a disease (error), but it is more important to understand the disease (error) rather than give medicine to it. If you can understand the error perfectly, it is much easier to find the solution.
Similarly, this article will see one of the important errors we regularly encounter, i.e., the “Subscript out of range” error in Excel VBA.
Table of contents
- Excel VBA Subscript Out of Range
- What is Subscript out of Range Error in Excel VBA?
- Why Subscript Out of Range Error Occurs?
- VBA Subscript Error in Arrays
- How to Show Errors at the End of the VBA Code?
- Recommended Articles
You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Subscript Out of Range (wallstreetmojo.com)
What is Subscript out of Range Error in Excel VBA?
For example, if you are referring to the sheet, not the workbook, then we get Run-time error ‘9’: “Subscript out of range.”
If you click on the “End” button, it will end the sub procedure. If you click on “Debug,” it will take you to the line of code where it encountered an error, and help will take you to the Microsoft website page.
Why Does Subscript Out of Range Error Occur?
As we said, as a doctor, it is important to find the deceased before thinking about the medicine. VBA “Subscript out of range” error occurs when the line of code does not read the object we entered.
For example, look at the below image. We have three sheets: Sheet1, Sheet2, and Sheet3.
Now in the code, we have written the code to select the sheet “Sales.”
Code:
Sub Macro2() Sheets("Sales").Select End Sub
If we run this code using the F5 key or manually, we will get the Run-time error ‘9’: “Subscript out of range.”
It is because we tried accessing the worksheet object “Sales,” which does not exist in the workbook. It is a run time error because it occurred while running the code.
Another common subscript error is when we refer to the workbook, which is not there. For example, look at the below code.
Code:
Sub Macro1() Dim Wb As Workbook Set Wb = Workbooks("Salary Sheet.xlsx") End Sub
The above code says variable WB should be equal to the workbook “Salary Sheet.xlsx.” As of now, this workbook is not open on the computer. If we run this code manually or through the F5 key, we will get Run time error 9: “Subscript out of Range.“
It is due to the workbook we are referring to which is either not open or does not exist at all.
VBA Subscript Error in Arrays
When you declare the array as the dynamic array, and if you don’t use the word DIM or REDIM in VBAThe VBA Redim statement increases or decreases the storage space available to a variable or an array. If Preserve is used with this statement, a new array with a different size is created; otherwise, the current variable’s array size is changed.read more to define the length of an array, we usually get the VBA “Subscript out of range” error. For example, look at the below code.
Code:
Sub Macro3() Dim MyArray() As Long MyArray(1) = 25 End Sub
In the above, we have declared the variable as an array but have not assigned a start and ending point. Rather, we have assigned the first array the value of 25.
If we run this code using the F5 key or manually, we will get Run time error ‘9’: “Subscript out of Range.”
To fix this issue, we need to assign the length of an array by using the “ReDim” word.
Code:
Sub Macro3() Dim MyArray() As Long ReDim MyArray(1 To 5) MyArray(1) = 25 End Sub
This code does not give any errors.
How to Show Errors at the End of the VBA Code?
If you do not want to see the error while the code is up and running but needs an error list at the end, then you need to use the “On Error Resume” error handler. For example, look at the below code.
Code:
Sub Macro1() Dim Wb As Workbook On Error Resume Next Set Wb = Workbooks("Salary Sheet.xlsx") MsgBox Err.Description End Sub
As we have seen, this code will throw Run time error 9: “Subscript out of range” in Excel VBA. But we must use the error handler On Error Resume Next in VBAVBA On Error Resume Statement is an error-handling aspect used for ignoring the code line because of which the error occurred and continuing with the next line right after the code line with the error.read more while running the code. So, we will not get any error messages. Rather, the end message box shows me the error description like this.
You can download the Excel VBA Subscript Out of Range Template here:- VBA Subscript Out of Range Template
Recommended Articles
This article has been a guide to VBA Subscript Out of Range. Here, we learned the Error called “Subscript out of range” (Run-time error’9′) in Excel VBA, along with practical examples and a downloadable template. Below you can find some useful Excel VBA articles: –
- Declare Global Variables in VBA
- VBA AutoFill
- Clear Contents in VBA
- Excel VBA UCase Function
Sometimes when we write and attempt to run sub-procedures in Excel VBA, Excel VBA returns a message box with the error message “Runtime error 9: Subscript out of range.”
The “Subscript out of range” error happens when we reference a non-existent collection member or a non-existent array element.
By the error, Excel VBA is telling us, “I have not found what you are looking for.”
This tutorial gives examples of specific causes of this error and how to fix it.
Before fixing the “Subscript out of range” error, you must identify its cause.
When you press the Debug button on the error message box, Excel VBA takes you to the statement that caused the error. By examining the line of code, you should be able to tell what caused the error. We outline some of the causes and solutions below.
Cause #1: Referencing a Non-Existent Item in a Collection
We can only access members of collections within their delimited ranges.
Therefore, attempting to access a collection member outside the defined scope will cause the “Subscription out of range” runtime error.
Suppose we have only Sheet1 and Sheet2 in our active workbook.
If we write the following sub-procedure and press F5 to run it:
We get the “Subscript out of range” error:
The error occurs because the Sheet3 object is not present in the Sheets collection, which consists of all the worksheets and chart sheets in the active workbook.
Therefore the code is referencing a non-existent entity in the Sheets collection.
How to Fix It
You can fix this error in any of the following ways:
- Create the non-existent object; in this case, add Sheet3 to the workbook.
- Check the spelling of the name of the collection member you want to access and ensure it is correct.
- In the Excel VBA code, refer to an object present in the collection; in this case, you can refer to either Sheet1 or Sheet2.
- Use the For Each…Next loop instead of referencing specific collection members. The loop allows us to loop through collection members and repeat particular actions, such as unhiding worksheets.
Also read: Not Enough Memory to Complete This Action in Excel – How to Fix?
Cause #2: Attempting to Access a Closed Workbook
If you try to access a closed workbook, you get the “Subscript out of range” error.
For example, if we have a closed workbook called “Employees” on our computer, running the following sub-procedure will generate the “Subscript out of range” error.
This error is generated because a closed workbook is not part of the collection of workbooks.
All the open workbooks on your computer make up the workbooks collection.
How to Fix It
You can use any of the following methods to fix the error.
- Open the workbook you want to access, then run the sub-procedure.
- Use the For Each…Next loop to check whether the workbook you wish to access is open. The loop goes through all the available workbooks and matches the name of the workbook you want to access against each open workbook. If a match is found, the workbook is open otherwise; the workbook is closed.
Cause #3: Referencing a Non-existent Array Element
If you reference a non-existent array element in your code, VBA displays the “Subscript out of range” to indicate something wrong with the code.
For example, the following code refers to an array element 11, which is not in the array declaration.
When we attempt to run the code, we get the “Subscript out of range” error.
How to Fix It
You can use any of the following techniques to solve the problem:
- Verify the upper and lower bounds of the array in the array declaration. If the dimensions are different from what you intended, adjust them accordingly.
- Ensure that you only refer to the array elements in the array declaration.
- Use LBound and UBound functions to direct the access of redimensioned arrays. The LBound function returns the lower boundary of the array, which can be either 0 or 1. The UBound function returns the upper limit of the array, which is equivalent to the number of items in the array.
- If the array dimensions are declared variables, ensure the variable names are spelled correctly.
Cause #4: Not Specifying the Number of Elements in an Array
If you declare an array but do not specify the number of elements in the array and attempt to access an element in the array, VBA returns the “Subscript out of range” error.
For example, the following code results in the error:
How to Fix It
- Explicitly specify the number of elements in the array in the array declaration.
Cause #5: Misspelling the name of a Workbook
If you misspell the name of the workbook you want to access, Excel VBA will return the “Subscript is out of range error.”
For example, if you want to activate a workbook named “Employees.xlsx,” the following code will not activate the workbook but return an error:
Although the workbook is open, the sub-procedure does not activate it because its name needs to be corrected.
How to Fix It
- Check the spelling of the workbook’s name in the sub-procedure and ensure it is correct.
Cause #6: Specifying an Invalid Element
Sometimes when you use the shorthand form of a subscript, you may mistakenly specify an invalid element.
For example, the shorthand for ActiveSheet.Range(“C3”) is [C3]. If this shorthand form of the subscript refers to an invalid element, you will get the “Subscript is out of range error.”
How to Fix It
Use a valid index or name for the collection.
This tutorial has given reasons and solutions for the “Subscript out of range” error. This error happens when we reference a non-existent collection member or a non-existent array element.
Examples of specific causes include
- Referencing a worksheet or workbook not present in the collection.
- Misspelling object names in the code.
- Referencing a non-existent array element.
- Not specifying the number of elements in the array.
- Attempting to access a closed workbook.
- Specifying an invalid element.
The solutions to the error include using the For Each…Next construct, instead of referencing specific items in the code and specifying the elements in an array.
We hope you found the tutorial helpful.
Other articles you may also like:
- Using Application.GetSaveAsFilename in VBA in Excel
- Using Application.EnableEvents in VBA in Excel
- SetFocus in Excel VBA – How to Use it?
- How to Open Excel Files Using VBA
- #NAME? Error in Excel – How to Fix!
- #NUM! Error in Excel – How to Fix it?
- SPILL Error in Excel – How to Fix?
Home / VBA / VBA Subscript Out of Range Runtime Error (Error 9)
Subscript Out of Range Error (Run Time: Error 9) occurs when you refer to an object or try to use a variable in a code that doesn’t exist in the code, in that case, VBA will show this error. As every code that you write is unique, so the cause of the error would be.
In the following example, you have tried to activate the “Sheet1” which is an object. But as you can see in the workbook no worksheet exists with the name “Sheet1” (instead you have “Sheet2”) so VBA show “Subscript Out of Range” to notify you that there’s something wrong with the code.
Subscript Out of Range
There could be one more situation when you have to face the error “Subscript Out of Range Error” when you are trying to declare a dynamic array but forget to use the DIM and ReDim statement to redefine the length of the array.
Now in the above code, you have an array with the name “myArray” and to make it dynamic we have initially left the array length blank. But before you add an item you need to redefine the array length using the ReDim statement.
And that’s the mistake we have made in the above code and VBA has returned the “Script Out of Range” error.
Sub myMacro()
Dim myArray() As Variant
myArray(1) = "One"
End Sub
How Do I Fix Subscript Out of Range in Excel?
The best way to deal with this Subscript Out of Range is to write effective codes and make sure to debug the code that you have written (Step by Step).
When you run a code step by step it is easy for you to know on which line of that code you have an error as VBA will show you the error message for Error 9 and highlight that line with yellow color.
The other thing that you can do is to use an “Error Handler” to jump to a specific line of error when it happens.
In the following code, we have written a line to activate the sheet but before that, we have used the goto statement to move to the error handler. In the error handler, you have a message box that shows you a message with the Err. Description that an error has occurred.
So, when you run this code and the “Sheet1” is not in the workbook where you are trying to activate it. It will show you a message box just like below.
And if the “Sheet1” is there then there won’t be any message at all.
Sub myMacro()
Dim wks As Worksheet
On Error GoTo myError
Sheets("Sheet1").Activate
myError:
MsgBox "There's an error in the code: " & Err.Description & _
". That means there's some problem with the sheet " & _
"that you want to activate"
End Sub
tgg Пользователь Сообщений: 12 |
Добрый вечер знатоки. Простой макрос стал прерываться ошибка runtime error 9 subscript out of range, долго искал причину.. а оказалось дело в следующем. При открытии другой Книги, или работая в другой книге в момент когда запускаются макросы (2 шт.каждые 60сек) в Книге1 и вылетает error Изменено: tgg — 16.03.2018 10:48:28 |
А где собственно вопрос? С уважением, |
|
tgg Пользователь Сообщений: 12 |
#3 27.03.2015 20:31:46 На строке With Worksheets(«Лист1») всё и происходит!
Изменено: tgg — 31.03.2015 22:50:24 |
||
Казанский Пользователь Сообщений: 8839 |
#4 27.03.2015 20:46:12 Начало второй процедуры:
Аналогично переделайте все квадратные скобки. |
||
tgg Пользователь Сообщений: 12 |
Вот в чём вопрос?? Изменено: tgg — 31.03.2015 22:50:35 |
1. Worksheets(«Лист1») — без указания принадлежности к книге, относится к активной в момент запуска макроса книге. Видимо, в ней нет листа Лист1. |
|
tgg Пользователь Сообщений: 12 |
Еще раз огромное спасибо!! |
Юрий М Модератор Сообщений: 60575 Контакты см. в профиле |
tgg, два момента: |
tgg Пользователь Сообщений: 12 |
#9 19.06.2015 22:03:22 Доброго времени суток! Не прошло и полгода …. Я к Вам с поклоном и вопросом. http://www.planetaexcel.ru/forum/?FID=8&PAGE_NAME=read&TID=30902 ), с той лишь разностью, что работает с диапазоном — If Not Intersect(ActiveCell, Range(«E18:E27»)) Is Nothing Then. Вот собственно сам макрос:
Но старая песня, опять при открытии другой книги excel этот макрос зачем-то срабатывает и встаёт на 2 строке. |
||
Johny Пользователь Сообщений: 2737 |
Когда открывается книга, то она становится активной, и поэтому Ваш диапазон Range(«E18:E27») относится уже к ОТКРЫТОЙ книге. There is no knowledge that is not power |
tgg Пользователь Сообщений: 12 |
Пробовались разные варианты, это первый вариант макроса, с указанием листа и принадлежности к книге. Но результат всегда был один и тот же. |
Johny Пользователь Сообщений: 2737 |
#12 19.06.2015 22:20:38
Ну так покажите эти «разные» варианты. There is no knowledge that is not power |
||
tgg Пользователь Сообщений: 12 |
Так они ведь не работают как надо! |
Rjn Пользователь Сообщений: 6 |
#14 16.03.2018 09:08:30 Добрый день!
|
||
Rjn Пользователь Сообщений: 6 |
В чем ошибка??? |
Hugo Пользователь Сообщений: 23251 |
Ведь естественно — если файл закрыт, то при попытке его сохранения должна быть ошибка. |
Sanja Пользователь Сообщений: 14838 |
#17 16.03.2018 09:19:33
Вы же выше сами написали, что
Макрос написан именно так, что файл должен быть предварительно открыт Согласие есть продукт при полном непротивлении сторон. |
||||
Rjn Пользователь Сообщений: 6 |
А где и как исправить макрос, что бы он работал при закрытом файле? |
vikttur Пользователь Сообщений: 47199 |
1. Код в сообщении следует оформлять кнопкой <…> |
vsahno Пользователь Сообщений: 42 |
#20 21.02.2019 19:08:28
У меня не были прописаны ПОЛНЫЕ ИМЕНА ФАЙЛОВ! — только название, без расширения: |
||
Дмитрий Минин Пользователь Сообщений: 2 |
#21 21.03.2023 10:15:59 Добрый день!
Прикрепленные файлы
|
||
Существует ли лист «Sheet1» в активной книге? |
|
Дмитрий Минин Пользователь Сообщений: 2 |
#23 21.03.2023 11:00:04
Понял ошибку и уже исправил. |
||
Workbooks | Worksheets | Array
The ‘subscript out of range‘ error in Excel VBA occurs when you refer to a nonexistent collection member or a nonexistent array element.
Place a command button on your worksheet and add the code lines below. To execute the code lines, click the command button on the sheet.
Workbooks
The Workbooks collection in Excel VBA contains all the Workbook objects that are currently open.
1. The code line below closes sales.xlsm.
Workbooks(«sales.xlsm»).Close
Result when there’s no open workbook with this name:
Note: to fix this ‘subscript out of range’ error (run-time error 9), open sales.xlsm before clicking the command button.
Worksheets
The Worksheets collection in Excel VBA contains all the Worksheet objects in a workbook. Our workbook has 3 worksheets.
1. The code line below tries to place the word Hello into cell A1 on the 4th worksheet.
Worksheets(4).Range(«A1»).Value = «Hello»
Result when you click the command button on the sheet:
Explanation: the ‘subscript out of range’ error pops up because there’s no 4th worksheet. To fix this error, change the 4 to a 1, 2 or 3 (or insert a new worksheet by clicking the plus sign).
Array
An array is a group of variables. In Excel VBA, you can refer to a specific variable (element) of an array by using the array name and the index number.
1. The first code line below declares a String array with name Films. The array consists of five elements.
2. Next, we initialize each element of the array.
3. The final code line tries to display the 6th element using a MsgBox.
Dim Films(1 To 5) As String
Films(1) = «Lord of the Rings»
Films(2) = «Speed»
Films(3) = «Star Wars»
Films(4) = «The Godfather»
Films(5) = «Pulp Fiction»
MsgBox Films(6)
Result when you click the command button on the sheet:
Explanation: the ‘subscript out of range’ error pops up because there’s no 6th element. To fix this error, change the 6 to a 1, 2, 3, 4 or 5 (or declare a String array with 6 elements).