I have a problem in excel Vba when I try to run this code, I have an error of subscript out of range:
Private Sub UserForm_Initialize()
n_users = Worksheets(Aux).Range("C1").Value
Debug.Print Worksheets(Aux).Range("B1:B" & n_users).Value
ListBox1.RowSource = Worksheets(Aux).Range("B1:B" & n_users).Value
ComboBox1.RowSource = Worksheets(Aux).Range("B1:B" & n_users).Value
ComboBox2.RowSource = Worksheets(Aux).Range("B1:B" & n_users).Value
End Sub
And Debug.Print works well, so the only problem is in Range(«B1:B» & n_users).Value.
asked Oct 19, 2013 at 15:15
user2898085user2898085
492 gold badges4 silver badges14 bronze badges
5
If the name of your sheet is «Aux», change each Worksheets(Aux)
reference to Worksheets("Aux")
. Unless you make Aux
a string variable, for example:
Dim Aux As String
Aux = "YourWorksheetName"
n_users = Worksheets(Aux).Range(C1).Value
you must use quatations around sheet references.
answered Oct 19, 2013 at 16:36
ARichARich
3,2004 gold badges30 silver badges56 bronze badges
1
Firstly, unless you have Aux
defined somewhere in the actual code, this will not work. The sheet-name reference must be a string value, not an empty variable (which ARich explains in his answer).
Second, the way in which you are trying to populate the rowsource value is incorrect. The rowsource property of a combobox is set using a string value that references the target range. By this I mean the same string value you would use in an excel formula to reference a cell in another sheet. For instance, if your worksheet is named «Aux» then this would be your code:
ComboBox1.RowSource = "Aux!B1:B" & n_users
I think you can also use named ranges. This link explains it a little.
answered Oct 19, 2013 at 18:13
Ross BrasseauxRoss Brasseaux
3,8411 gold badge27 silver badges46 bronze badges
2
I can’t see how you can get an Error 9 on that line. As others have pointed out repeatedly, the place you’ll get it is if the variable Aux doesn’t have a string value representing the name of a worksheet. That aside, I’m afraid that there is a LOT wrong with that code. See the comments in the below revision of it, which as near as I can figure is what you’re trying to get to:
Private Sub UserForm_Initialize()
'See below re this.
aux = "Sheet2"
'You should always use error handling.
On Error GoTo ErrorHandler
'As others have pointed out, THIS is where you'll get a
'subscript out of range if you don't have "aux" defined previously.
'I'm also not a fan of NOT using Option Explicit, which
'would force you to declare exactly what n_users is.
'(And if you DO have it declared elsewhere, I'm not a fan of using
'public variables when module level ones will do, or module
'level ones when local will do.)
n_users = Worksheets(aux).Range("C1").Value
'Now, I would assume that C1 contains a value giving the number of
'rows in the range in column B. However this:
'*****Debug.Print Worksheets(aux).Range("B1:B" & n_users).Value
'will only work for the unique case where that value is 1.
'Why? Because CELLS have values. Multi-cell ranges, as a whole,
'do not have single values. So let's get rid of that.
'Have you consulted the online Help (woeful though
'it is in current versions) about what the RowSource property
'actually accepts? It is a STRING, which should be the address
'of the relevant range. So again, unless
'Range("B1:B" & n_users) is a SINGLE CELL that contains such a string
'(in which case there's no point having n_users as a variable)
'this will fail as well when you get to it. Let's get rid of it.
'****ListBox1.RowSource = Worksheets(aux).Range("B1:B" & n_users).Value
'I presume that this is just playing around so we'll
'ignore these for the moment.
'ComboBox1.RowSource = Worksheets(aux).Range("B1:B" & n_users).Value
'ComboBox2.RowSource = Worksheets(aux).Range("B1:B" & n_users).Value
'This should get you what you want. I'm assigning to
'variables just for clarity; you can skip that if you want.
Dim l_UsersValue As Long
Dim s_Address As String
l_UsersValue = 0
s_Address = ""
'Try to get the n_users value and test for validity
On Error Resume Next
l_UsersValue = Worksheets(aux).Range("C1").Value
On Error GoTo ErrorHandler
l_UsersValue = CLng(l_UsersValue)
If l_UsersValue < 1 Or l_UsersValue > Worksheets(aux).Rows.Count Then
Err.Raise vbObjectError + 20000, , "User number range is outside acceptable boundaries. " _
& "It must be from 1 to the number of rows on the sheet."
End If
'Returns the cell address
s_Address = Worksheets(aux).Range("B1:B" & n_users).Address
'Add the sheet name to qualify the range address
s_Address = aux & "!" & s_Address
'And now that we have a string representing the address, we can assign it.
ListBox1.RowSource = s_Address
ExitPoint:
Exit Sub
ErrorHandler:
MsgBox "Error: " & Err.Description
Resume ExitPoint
End Sub
answered Oct 19, 2013 at 20:09
Alan KAlan K
1,9473 gold badges19 silver badges30 bronze badges
5
Excel VBA Subscript out of Range
VBA Subscript out of Range or majorly knows as Run-Time Error 9 happens when we select such cell or sheet or workbook which actually does not come under range or criteria defined in Excel. It is like we have selected the range of 100 cells or a column and we have called out the values stored in 120 cells of the same column. Which means that we are going out of range to select and call out the values which are not in our defined criteria. When this kind of situation happens, we get a “Run-Time Error 9” message while compiling or running the code. VBA Subscript out of Range error message guides us to rectify the error which is related to the range we have selected in Excel.
Example of Excel VBA Subscript out of Range
Below are the different examples of VBA Subscript out of Range in Excel.
You can download this VBA Subscript out of Range Excel Template here – VBA Subscript out of Range Excel Template
VBA Subscript out of Range – Example #1
We will first consider a simple example. For this, we need to go to VBA windows and add a new module by going in Insert menu option as shown below.
We will get a white blank window of Module. This is where we need to do coding work.
Now write Subcategory of performed function, for best practice keep the name of a function in Subcategory, as we did here for VBA Subscript out of Range.
Code:
Sub Subscript_OutOfRange1() End Sub
Here in excel, we have only one sheet named as “Sheet1” as shown below.
But we will write a code to select a sheet which is not even added and see what happens.
Now go to VBA window and write Sheets(2) followed by Select function as shown below. Which means, we are selecting Sheet sequence of 2nd position with Select function.
Code:
Sub Subscript_OutOfRange1() Sheets(2).Select End Sub
Now compile the complete code or do it step by step to know which part of the code is an error. As we have only one line of code, we can directly run the code by clicking on the play button below the menu bar. We will get an error Message saying “Run-Time error 9, Subscript out of range” in the VBA as shown below.
This shows that we are trying to select that sheet which doesn’t exist. If we add a new sheet or change the sheet sequence in code from 2nd to 1st then we may get a successful code run. Let’s add another sheet and see what happens.
Now again run the code. And as we did not see any error, which means our code completes the successful run.
VBA Subscript out of Range – Example #2
In another example, we will see again a simple code of activating a Worksheet. For this again we will write the code. Start writing the Subcategory in the name of a performed function or in any other name as shown below.
Code:
Sub Subscript_OutOfRange2() End Sub
Now with the help of Worksheet, we will activate Sheet1 as shown below.
Code:
Sub Subscript_OutOfRange2() Worksheets("Sheet1").Activate End Sub
Now compile the complete code and run. We will notice there is no error message been popped-up which means code run is successful. Now let’s put the space in between “Sheet 1”
Again compile and run the code.
As we can see above, even if our complete process and way of writing the code are correct but we have taken in correct sheet name as “Sheet 1”. Which in reality has no space between “Sheet1”.
This shows, there are the still chances of getting an error if do not spell or write correct sheet name or workbook name.
VBA Subscript out of Range – Example #3
In this example, we will see how choosing incorrect Array range may create and show Run-time error 9. Start writing Subcategory again in the name of the performed function as shown below.
Code:
Sub Subscript_OutOfRange3() End Sub
Now with the help of DIM define an Array of any size and gives it to String or Integers. Which depends, what we want to store in Array, numbers or text.
Here we have considered an array of 2×3 as String as shown below.
Code:
Sub Subscript_OutOfRange3() Dim SubArray(2, 3) As String End Sub
By this, it will form a table for 2 rows and 3 columns and we can store any values as per our need. As we have selected String then we will consider text or alphabets in it.
Now in the second line of code, select the created array but with an extra or more column and assign a text as ABC or any other text as per your choice. Here, we have selected an Array of 2×5 as shown below.
Code:
Sub Subscript_OutOfRange3() Dim SubArray(2, 3) As String SubArray(2, 5) = ABC End Sub
Now compile and run the code. As we can see in below screenshot, we got a VBA Subscript out of Range error message of Run-time error 9.
Reason for getting this error is because we have selected an incorrect Array range within 2 extra columns from 2×3 to 2×5, which is beyond the limit of code. Now if we again select the correct range of array as 2×3 and see what happens.
After compiling and running the code. We will see we did not receive any error which means our code run was successful.
Pros of Excel VBA Subscript out of Range
- VBA Subscript out of Range allows us to know what kind of error has happened. So that we can specifically find the solution of the obtained error code.
- As VBA subscript out of range ‘Run-time error 9’ is quite useful in knowing what kind of error has occurred in excel.
Things to Remember
- It is recommended to use Subcategory in the name of the performed function with a sequence of code so that it would be easy to track it properly.
- Save the file as Macro-Enabled Workbook to avoid losing written code.
- If you have huge lines of code then it is better to compile each line of code one by one by pressing F8 key. This method compiles each step of code so that we can directly know which portion of code actually has the error in the first go.
Recommended Articles
This has been a guide to Excel VBA Subscript out of Range. Here we discussed why VBA Subscript out of Range error occurs (Run-time Error 9) along with some practical examples and downloadable excel template. You can also go through our other suggested articles –
- VBA IsError
- VBA Get Cell Value
- VBA On Error
- VBA XML
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 |
Еще раз огромное спасибо!! |
Юрий М Модератор Сообщений: 60394 Контакты см. в профиле |
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 Пользователь Сообщений: 23139 |
Ведь естественно — если файл закрыт, то при попытке его сохранения должна быть ошибка. |
Sanja Пользователь Сообщений: 14837 |
#17 16.03.2018 09:19:33
Вы же выше сами написали, что
Макрос написан именно так, что файл должен быть предварительно открыт Согласие есть продукт при полном непротивлении сторон. |
||||
Rjn Пользователь Сообщений: 6 |
А где и как исправить макрос, что бы он работал при закрытом файле? |
vikttur Пользователь Сообщений: 47199 |
1. Код в сообщении следует оформлять кнопкой <…> |
vsahno Пользователь Сообщений: 42 |
#20 21.02.2019 19:08:28
У меня не были прописаны ПОЛНЫЕ ИМЕНА ФАЙЛОВ! — только название, без расширения: |
||
When running a VBA procedure, you might receive this error message
“Run-time error ‘9’, Subscript out of range”. In this article, we will talk about the possible reasons for the occurrence of this error and the ways to fix it.
According to our recent review, there are four categories that can trigger this error:
- Referring to a nonexistent element
- Wrong collection member
- Unidentified element
- Shorthand script
We are going to take a look at each of these categories and show you how to generate this error and share the best way to fix it.
Referring to a nonexistent element
In some cases, you might have referenced an element (a workbook, worksheet, array, etc.) in the code that doesn’t exist. It is also possible that the subscript is either smaller or larger than the range of possible subscripts.
You referred to a nonexistent Worksheet
To generate this error, open the VBA editor and write the following code to select the sheet “customers” in Module1.
Sub Test1() Sheets("customers").Select End Sub
If you run the code, you will have the error message.
The reason for this error is the fact that there is no sheet named “customers” in the workbook. Our workbook has three sheets named respectively Sheet1, Sheet2 and Sheet3.
To fix the error, create a worksheet named “customers” or rename any of the three existing sheets and run the macro again.
You referred to a Workbook that is not opened on your computer
If you run the code below, you will have the error code because you will be referring to a workbook that is not opened on your computer.
Sub Macro3( B ) Dim Wbk As Workbook Set Wbk = Workbooks("Employees.xls") End Sub
Wrong collection member
The subscript may be larger or smaller than the range of possible subscripts.
To generate this error, run the following code:
Sub Macro( ) Dim PriceArray(5 To 10 ) As Integer PriceArray(3) = 20 End Sub
Or
Sub Macro( ) Dim PriceArray(5 To 10 ) As Integer PriceArray(15) = 20 End Sub
The error will be triggered after running any of the two macros above because the PriceArray has been dimensioned from 5 to 10. But the code is referring to a subscript of index 3 (lower than 5) and 15 for the second macro (larger than 10). Elements of arrays and members of collections can only be accessed within their defined ranges.
That is why it is important to check the declaration of the array to verify it’s upper and lower bounds. It is also advisable to use the UBound and LBound functions to condition array accesses if you are working with arrays that are redimensioned.
Unidentified element
You declared an array but didn’t specify the number of elements
The following code will generate the error:
Sub Macro2( ) Dim PriceArray( ) As Integer PriceArray(5) = 20 End Sub
The error occurs because when declaring the array named PriceArray, the number of elements was not specified. In fact, Visual Basic does not implicitly dimension unspecified array range as 0 to 10.
To avoid the error, you must explicitly specify the number of elements in the array as in the code below:
Sub Macro3( ) Dim PriceArray(0 To 10 ) As Integer PriceArray(5) = 20
Shorthand script
You might have used a shorthand form of the subscript and it specifies an invalid element. Therefore, it is recommended that you use a valid key name and index for the collection.
For example [A10] is the shorthand for ActiveSheet.Range(A10). This means that instead of writing ActiveSheet.Range(A10).Select you can just write [A1].Select
If you don’t have a good knowledge of shorthand scripting, avoid using it because it can generate many errors, not just the “Subscript is out of range” error.
The aim of this article was to explain the possible reasons (the list is not exhaustive) for the occurrence of the “Subscript is out of range” error. Through a step by step tutorial, you have been able to fix the error. We hope it has been useful.
Номер ошибки: | Ошибка во время выполнения 9 | |
Название ошибки: | Subscript out of range | |
Описание ошибки: | Elements of arrays and members of collections can only be accessed within their defined ranges. | |
Разработчик: | Microsoft Corporation | |
Программное обеспечение: | Windows Operating System | |
Относится к: | Windows XP, Vista, 7, 8, 10, 11 |
Обзор «Subscript out of range»
Как правило, практикующие ПК и сотрудники службы поддержки знают «Subscript out of range» как форму «ошибки во время выполнения». Когда дело доходит до программного обеспечения, как Windows Operating System, инженеры могут использовать различные инструменты, чтобы попытаться сорвать эти ошибки как можно скорее. Ошибки, такие как ошибка 9, иногда удаляются из отчетов, оставляя проблему остается нерешенной в программном обеспечении.
После установки программного обеспечения может появиться сообщение об ошибке «Elements of arrays and members of collections can only be accessed within their defined ranges.». Во время возникновения ошибки 9 конечный пользователь может сообщить о проблеме в Microsoft Corporation. Microsoft Corporation может устранить обнаруженные проблемы, а затем загрузить измененный файл исходного кода, позволяя пользователям обновлять свою версию. Чтобы исправить такие ошибки 9 ошибки, устанавливаемое обновление программного обеспечения будет выпущено от поставщика программного обеспечения.
Почему возникает ошибка времени выполнения 9?
В большинстве случаев вы увидите «Subscript out of range» во время загрузки Windows Operating System. Вот три наиболее распространенные причины, по которым происходят ошибки во время выполнения ошибки 9:
Ошибка 9 Crash — Ошибка 9 может привести к полному замораживанию программы, что не позволяет вам что-либо делать. Если данный ввод недействителен или не соответствует ожидаемому формату, Windows Operating System (или OS) завершается неудачей.
Утечка памяти «Subscript out of range» — если есть утечка памяти в Windows Operating System, это может привести к тому, что ОС будет выглядеть вялой. Есть некоторые потенциальные проблемы, которые могут быть причиной получения проблем во время выполнения, с неправильным кодированием, приводящим к бесконечным циклам.
Ошибка 9 Logic Error — логическая ошибка возникает, когда компьютер производит неправильный вывод, даже если вход правильный. Это видно, когда исходный код Microsoft Corporation включает дефект в анализе входных данных.
Subscript out of range проблемы часто являются результатом отсутствия, удаления или случайного перемещения файла из исходного места установки Windows Operating System. В большинстве случаев скачивание и замена файла Microsoft Corporation позволяет решить проблему. Мы также рекомендуем выполнить сканирование реестра, чтобы очистить все недействительные ссылки на Subscript out of range, которые могут являться причиной ошибки.
Распространенные сообщения об ошибках в Subscript out of range
Обнаруженные проблемы Subscript out of range с Windows Operating System включают:
- «Ошибка программы Subscript out of range. «
- «Ошибка программного обеспечения Win32: Subscript out of range»
- «Subscript out of range столкнулся с проблемой и закроется. «
- «Subscript out of range не может быть найден. «
- «Subscript out of range не может быть найден. «
- «Проблема при запуске приложения: Subscript out of range. «
- «Файл Subscript out of range не запущен.»
- «Отказ Subscript out of range.»
- «Неверный путь к приложению: Subscript out of range.»
Эти сообщения об ошибках Microsoft Corporation могут появляться во время установки программы, в то время как программа, связанная с Subscript out of range (например, Windows Operating System) работает, во время запуска или завершения работы Windows, или даже во время установки операционной системы Windows. Документирование проблем Subscript out of range в Windows Operating System является ключевым для определения причины проблем с электронной Windows и сообщения о них в Microsoft Corporation.
Причины ошибок в файле Subscript out of range
Проблемы Subscript out of range могут быть отнесены к поврежденным или отсутствующим файлам, содержащим ошибки записям реестра, связанным с Subscript out of range, или к вирусам / вредоносному ПО.
Более конкретно, данные ошибки Subscript out of range могут быть вызваны следующими причинами:
- Поврежденная или недопустимая запись реестра Subscript out of range.
- Вирус или вредоносное ПО, повреждающее Subscript out of range.
- Другая программа (не связанная с Windows Operating System) удалила Subscript out of range злонамеренно или по ошибке.
- Другое приложение, конфликтующее с Subscript out of range или другими общими ссылками.
- Поврежденная загрузка или неполная установка программного обеспечения Windows Operating System.
Продукт Solvusoft
Загрузка
WinThruster 2022 — Проверьте свой компьютер на наличие ошибок.
Совместима с Windows 2000, XP, Vista, 7, 8, 10 и 11
Установить необязательные продукты — WinThruster (Solvusoft) | Лицензия | Политика защиты личных сведений | Условия | Удаление