Индекс выходит за пределы допустимого диапазона (ошибка 9)
К элементам массива и коллекции можно обращаться только в пределах их допустимых диапазонов. Эта ошибка имеет следующие причины и способы решения:
Вы обратились к несуществующему элементу массива. Возможно, заданный индекс выходит за пределы диапазона допустимых индексов или размеры массива не соответствуют параметрам, присвоенным на данном этапе приложения. Проверьте верхнюю и нижнюю границы, заданные при объявлении массива. Используйте функции UBound и LBound, чтобы обуславливать доступ к массивам, если вы работаете с массивами, которые имеют другие измерения. Если индекс указан как переменная, проверьте правильность имени переменной.
Массив был объявлен без определения числа элементов. Например, ниже показано сообщение об ошибке, полученное при запуске такого кода:
Вы обратились к несуществующему элементу коллекции. Вместо указания индексов попробуйте обработать элементы массива с помощью конструкции For Each. Next.
Вы использовали сокращенную форму индекса, который неявно указывал недопустимый элемент. Например, если вы используете ! оператор с коллекцией — ! неявно указывает ключ. Например, объект!ключевоеИмя. значение эквивалентно объекту. элемент (ключевоеИмя). значение. В этом случае возникает ошибка, если ключевоеИмя обозначает недопустимый ключ в коллекции. Чтобы исправить ошибку, используйте правильное имя ключа или индекс для коллекции.
Для получения дополнительной информации выберите необходимый элемент и нажмите клавишу F1 (для Windows) или HELP (для Macintosh).
Хотите создавать решения, которые расширяют возможности Office на разнообразных платформах? Ознакомьтесь с новой моделью надстроек Office. Надстройки Office занимают меньше места по сравнению с надстройками и решениями VSTO, и вы можете создавать их, используя практически любую технологию веб-программирования, например HTML5, JavaScript, CSS3 и XML.
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
How to Fix MS Access Subscript Out of Range Error
Ms Access Subscript Out of Range error often occurred when you try to import Ms Excel database to Ms Access or trying to split the database. The possible cause of subscript out of range error:
1. Too many column in Excel spreadsheet
2. Corruption in Excel file.
3. Access cannot translate the formatted or modified Excel fields.
4. Disabled Macros from Excel to Access.
5. Using tool wizards in creating query or other objects.
6. Error code in VBA code or Macros programming.
(Sample of the Subscript error when importing database)
Ms Access Subscript Out Of Range (1)
The solutions for solving the Subscript Out of Range error may be vary depends on the error source. Here are some way to resolve it based on the problem:
1. For Too many Excel Column, the best way to fix it is by reduce the column amount. Just save the crucial, important, or the primary key fields. Or, you can split the database into several databases.
2. For corrupted file, try the repair tools in Ms. Excel. Make sure to back up the spreadsheet first.
3. In the modified Excel fields, you need to remove the format or modified value and convert them into the simplest format. If the field is equation field (summarized, or other calculation) or has formula (like If else), try to not import them and recreate the said fields in the Access instead with Access syntax.
4. For Disabled Macros, you will receive a pop up or warning to inform you. You only have to enable it.
5. The query wizard can cause the problem. Try to create the query and add the tables manually.
Ms Access Subscript Out Of Range (2)
6. So far, the error caused by Error code in the VBA code is the worse and harder to fix. You need to recheck all of the code lines to find the error, typos, or wrong syntax. Make sure you can answer these following question:
a. Check the declared array. Is the array exist? Do you specify the number of elements?
b. If you using subscript (!), does the syntax is right?
The tutorial above covers the most common Subscript Out of Range error. Please note that there still many possible cause and other solutions to solve and fix the problem.
Ошибка «Subscript out of range»
Вложения
![]() | Книга1.rar (765.6 Кб, 11 просмотров) |
Ошибка «Run-time error «9»: Subscript out of range»
Доброго времени суток. Программа выводит ошибку «Run-time error «9»: Subscript out of range», но не.
Ошибка «Subscript out of range» при работе с индексами массива
Добрый день! Никак не могу понять природу ошибки. Массиву присваивается диапазон значений, но как.

Всем привет, есть код : Private Sub cmd_start_Click() Dim x(4) As Single, y(7) As Single, S.
Ошибка с векторами «expression:vector subscript out of range»
Здваствуйте, при запуске программы вылазит ошибка «expression:vector subscript out of range».
у вас нет в модулях обязательной строки Option Explicit и у вас не проходит компиляция
следовательно невозможно гарантировать выполнение и то, что другой модуль знает это имя
Решение
pasha7598, смотрю на строки кода (рар у меня не читается) и думаю, а зачем там оператор With?
Если Worksheets(НовыйЛист) и Worksheets(НазваниеЛиста) находятся оба в Workbooks(НазваниеКниги), то он просто не нужен, а если книги разные, то тогда ясно почему вылетает ошибка, надо перед одним из листов поставить точку.
Добавлено через 2 минуты
Или активной в момент выполнения этого кода является не та книга, которую вы бы хотели
Почему выдает ошибку subscript out of range?
Почему выдает ошибку Почему выдает ошибку subscript out of range?
во всех строка где находится ActiveWorkbook.Worksheets(List).Cells(k, 2)
(не засунул под сode> т.к все русское меняет на иероглифы)
Option Base 1
Dim Ном1 As Integer, Группа1 As Integer, Ячейка As Integer
Dim Инф1 As Integer, Мат1 As Integer, ПСП1 As Integer
Dim ПТАКТ1 As Integer, Колдв As Integer
Dim Србал(1 To 4) As Currency
Public Фам1 As String
Public List As String
Public k As Integer
Private Sub Дан_Экзамен_Initialize()
k = 4
Workbooks.Add
Ном1 = ActiveWorkbook.Worksheets(List).Cells(k, 1)
Группа1 = ActiveWorkbook.Worksheets(List).Cells(k, 2)
Фам1 = ActiveWorkbook.Worksheets(List).Cells(k, 3)
Инф1 = ActiveWorkbook.Worksheets(List).Cells(k, 4)
Мат1 = ActiveWorkbook.Worksheets(List).Cells(k, 5)
ПСП1 = ActiveWorkbook.Worksheets(List).Cells(k, 6)
ПТАКТ1 = ActiveWorkbook.Worksheets(List).Cells(k, 7)
Колдв = ActiveWorkbook.Worksheets(List).Cells(k, 8)
Номер.Value = Ном1
Ввод_Фам.Value = Фам1
Ввод_Группа.Value = Группа1
Выбор_оценка.Value = Инф1
Выбор_Оценка1.Value = Мат1
Выбор_Оценка2.Value = ПСП1
Выбор_Оценка3.Value = ПТАКТ1
Ввод_дв.Value = Колдв
For j = 1 To 4
Србал(j) = ActiveWorkbook.Worksheets(List).Cells(14, j + 3)
Next j
Вывод_ср1.Value = Србал(1)
Вывод_ср2.Value = Србал(2)
Вывод_ср3.Value = Србал(3)
Вывод_ср4.Value = Србал(4)
Выбор_оценка.RowSource = «k5:k8»
Выбор_Оценка1.RowSource = «k5:k8»
Выбор_Оценка2.RowSource = «k5:k8»
Выбор_Оценка3.RowSource = «k5:k8»
End Sub
Private Sub Выбор_Оценка_Change()
Инф1 = Выбор_оценка.Value
End Sub
Private Sub Выбор_Оценка1_Change()
Мат1 = Выбор_Оценка1.Value
End Sub
Private Sub Выбор_Оценка2_Change()
ПСП1 = Выбор_Оценка2.Value
End Sub
Private Sub Выбор_Оценка3_Change()
ПТАКТ1 = Выбор_Оценка3.Value
End Sub
Private Sub Кн_Ввод_Click()
ActiveWorkbook.Worksheets(List).Cells(k, 4) = Инф1
ActiveWorkbook.Worksheets(List).Cells(k, 5) = Мат1
ActiveWorkbook.Worksheets(List).Cells(k, 6) = ПСП1
ActiveWorkbook.Worksheets(List).Cells(k, 7) = ПТАКТ1
For i = 4 To 7
If ActiveWorkbook.Worksheets(List).Cells(k, i) = 2 Then Колдв = Колдв + 1
Next i
ActiveWorkbook.Worksheets(List).Cells(k, 8) = Колдв
Ввод_дв.Value = Колдв
For j = 1 To 4
Србал(j) = 0
For M = 4 To 13
Србал(j) = Србал(j) + ActiveWorkbook.Worksheets(List).Cells(M, j + 3)
Next M
Србал(j) = Србал(j) / 10
ActiveWorkbook.Worksheets(List).Cells(14, j + 3) = Србал(j)
Next j
Вывод_ср1.Value = Србал(1)
Вывод_ср2.Value = Србал(2)
Вывод_ср3.Value = Србал(3)
Вывод_ср4.Value = Србал(4)
End Sub
Private Sub Кн_Выход_Click()
Dim M As String, T As String, R As String
Dim St As String
M = «Хотите закончить работу?»
St = vbYesNo + vbCritical + vbDefaultButton2
T = «Выход из программы!»
R = MsgBox(M, St, T)
If R = vbYes Then
Unload Me
End If
End Sub
Private Sub Кн_Редактировать_Click()
Номер.Enabled = True
Ввод_Фам.Enabled = True
Выбор_оценка.Enabled = True
Выбор_Оценка3.Enabled = True
Выбор_Оценка1.Enabled = True
Выбор_Оценка2.Enabled = True
Ввод_Группа.Enabled = True
End Sub
Private Sub Счет_SpinDown()
Номер.Enabled = False
Ввод_Фам.Enabled = False
Выбор_оценка.Enabled = False
Выбор_Оценка3.Enabled = False
Выбор_Оценка1.Enabled = False
Выбор_Оценка2.Enabled = False
Ввод_Группа.Enabled = False
If k > 4 Then k = k + 1
Ном1 = ActiveWorkbook.Worksheets(List).Cells(k, 1)
Группа1 = ActiveWorkbook.Worksheets(List).Cells(k, 2)
Фам1 = ActiveWorkbook.Worksheets(List).Cells(k, 3)
Инф1 = ActiveWorkbook.Worksheets(List).Cells(k, 4)
Мат1 = ActiveWorkbook.Worksheets(List).Cells(k, 5)
ПСП1 = ActiveWorkbook.Worksheets(List).Cells(k, 6)
ПТАКТ1 = ActiveWorkbook.Worksheets(List).Cells(k, 7)
Колдв = ActiveWorkbook.Worksheets(List).Cells(k, 8)
Номер.Value = Ном1
Ввод_Фам.Value = Фам1
Ввод_Группа.Value = Группа1
Выбор_оценка.Value = Инф1
Выбор_Оценка1.Value = Мат1
Выбор_Оценка2.Value = ПСП1
Выбор_Оценка3.Value = ПТАКТ1
Ввод_дв.Value = Колдв
End Sub
Private Sub Счет_SpinUp()
Номер.Enabled = False
Ввод_Фам.Enabled = False
Выбор_оценка.Enabled = False
Выбор_Оценка3.Enabled = False
Выбор_Оценка1.Enabled = False
Выбор_Оценка2.Enabled = False
Ввод_Группа.Enabled = False
Subscript out of range (Error 9)
Elements of arrays and members of collections can only be accessed within their defined ranges. This error has the following causes and solutions:
You referenced a nonexistent array element. The subscript may be larger or smaller than the range of possible subscripts, or the array may not have dimensions assigned at this point in the application. Check the declaration of the array to verify its upper and lower bounds. Use the UBound and LBound functions to condition array accesses if you are working with arrays that are redimensioned. If the index is specified as a variable, check the spelling of the variable name.
You declared an array but didn’t specify the number of elements. For example, the following code causes this error:
You referenced a nonexistent collection member. Try using the For Each. Next construct instead of specifying index elements.
You used a shorthand form of subscript that implicitly specified an invalid element. For example, when you use the ! operator with a collection, the ! implicitly specifies a key. For example, object!keyname. value is equivalent to object. item (keyname). value. In this case, an error is generated if keyname represents an invalid key in the collection. To fix the error, use a valid key name or index for the collection.
For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).
Interested in developing solutions that extend the Office experience across multiple platforms? Check out the new Office Add-ins model. Office Add-ins have a small footprint compared to VSTO Add-ins and solutions, and you can build them by using almost any web programming technology, such as HTML5, JavaScript, CSS3, and XML.
Support and feedback
Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.



