Sometimes the users face the error of subscript out of range in access. This error occurs when you trying to reference an index for a collection that is invalid. Most likely, the index in Windows doesn’t actually include .xls. The index for the windows should be as same as the name of the displayed workbook in the title bar of Excel. Well, there can be many other reasons for subscript out of range access import error.
Reasons Behind Subscript Out of Range Error
The possible reasons for this error are given below:
- In the Excel spreadsheet presence of an excessive number of columns.
- There can be some corruption issues that occurred in Excel files.
- Access is unable to translate the formatted or calculated Excel fields.
- While using the disabled Macros to access Excel.
These are the reasons responsible for the error. Now, let’s forward to the methods to resolve this issue.
Methods to Fix Error of Subscript Out of Range in Access
Subscript Out of Range Error is not a big issue that requires so much professional knowledge to fix. Generally, it occurs because of silly mistakes. Review all the given below checklist for fixing the error by making a few adjustment settings.
Method#1: Don’t Put Anything Over the Limit
Firstly, check out how many numbers of columns are present in your Excel spreadsheet? It’s necessary because MS Access Table can not consist of more than 255 number of files.
The best option to resolve this error or Subscript Out of Range Access import by reducing the unwanted column numbers. Only keep those columns that contain important data or the primary key.
The second step is that you can use is splitting the Access database
Method#2: Remove the Calculated Columns
If your Excel workbook consists of any calculated column and you are transferring it Access directly. Then it may create Subscript Out of Range Error. As it’s found that the Access database fails in transferring the formatted or calculated Excel fields.
So, for this, you have to copy the calculated column. After then only paste the calculated column’s value into a new column. At last, delete the calculated column.
Method#3: Make Your Access or Excel Error Free
Just make a quick move over complete your Excel spreadsheet, so that no error will found in your Excel workbook. It can help you to resolve the subscript out of range in access error.
It’s necessary to check because if you are importing an error in an Excel spreadsheet into Access, then it will harm your Excel database. As a result, you will get an error of subscript out of range in the access. So it’s better to go for a regular check.
The same rule of making the Access database error fee is also applicable if you are facing the error while splitting the Access database.
Method#4: Enable Your Disabled Macros
The steps are below for enabling and disabling Macros in all MS Office files.
When you open a file that shows the error of disabled macro then at the top bar, you will a yellow message bar along with the enable content button.
Here are the steps to enable it and fix the subscript out of range access import
- Firstly, tap on the file.
- Now, go to the security warnings section and click on the enable content.
- Select advanced options.
- A dialog box of MS Office security options will pop-up. From this, choose the option of enable content for this session, for each of the Macros.
- At last, click on OK.
Method#5: Professional Method
There is an alternative solution to fix the subscript out of range in access error. This contains a third-party tool that you can try. There is professional third-party software i.e, Access Database Recovery Tool. It can easily repair the subscript out of range import issue easily. It comes with some advanced features which are given below:
Features
- It can easily repair corrupt of MDB and ACCDB files.
- Also resolves the head corruption and the data misalignment issues.
- Have the tendency to restore, OLE, MEMO, & BLOB data of MS Access.
- Supports all Windows OS edition.
Wrap Up
If you have gone through the above post sincerely, then you have got a perfect idea to fix the error. Now, you can work according to these methods and can fix the subscript out of range in access error. As we have discussed the different methods. If we talk about the best, then you can opt for the Access Database Recovery Tool. This can easily fix this error without any consequences. The other methods contain many limitations and also consumes time. So choose the best for a better experience.
- Remove From My Forums
-
Question
-
I’ve created two identical tables in two different databases. The one gets no subscript errors, the other does. I’ve triple checked that all the field names and properties are IDENTICAL. Are there any other factors that would be causing
the subscript error?
Answers
-
Hi W85,
Can you make sure that the following suggestions?
1. The data type in the Excel sheet columns correspond to the data types in the Access table
2. You may want to make sure Excel sheet has no hidden columns or rows. Others have ever encountered a such a problem with one Excel sheet that gave a «subscript out of
range» message.As for the problem, please try to highlight all columns and then select the command to «unhide columns» in the format menu. Although I had no hidden columns, this command
itself was sufficient for the Excel sheet to adjust itself and allow it to be imported into Access. It seems that Access is very sensitive to certain formatting situations in Excel that prevent Excel tables from being imported.Hope this can help you to resolve the problem.If your problem persists, just
let me know, I will try to help you.Best Regards,
Bruce Song [MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
-
Marked as answer by
Friday, July 8, 2011 11:29 AM
-
Marked as answer by
Подстрочный индекс Excel VBA вне допустимого диапазона
Индекс вне диапазона — это ошибка, с которой мы сталкиваемся в VBA, когда пытаемся сослаться на что-то или на переменную, которая не существует в коде, например, предположим, что у нас нет переменной с именем x, но мы используем функцию msgbox для x, которую мы столкнется с ошибкой нижнего индекса вне диапазона.
Ошибка VBA Subscript out of range возникает из-за того, что объект, к которому мы пытаемся получить доступ, не существует. Это тип ошибки в Кодирование VBAКод VBA относится к набору инструкций, написанных пользователем на языке программирования приложений Visual Basic в редакторе Visual Basic (VBE) для выполнения определенной задачи.читать далее, и это «Ошибка времени выполнения 9». Важно понимать принципы написания эффективного кода, и еще более важно понимать ошибка вашего кода VBAОбработка ошибок VBA относится к устранению различных ошибок, возникающих при работе с VBA. читать далее для эффективной отладки кода.
Если ваша ошибка кодирования, и вы не знаете, что это за ошибка, когда вы ушли.
Врач не может дать лекарство своему пациенту, не зная, что это за болезнь. Конечно, и врачи, и пациенты знают, что есть болезнь (ошибка), но важнее понять болезнь (ошибку), чем давать от нее лекарство. Если вы можете прекрасно понять ошибку, то найти решение будет намного проще.
На аналогичном примечании в этой статье мы увидим одну из важных ошибок, с которыми мы обычно сталкиваемся регулярно, то есть ошибку «Нижний индекс вне диапазона» в Excel VBA.

Вы можете использовать это изображение на своем веб-сайте, в шаблонах и т. д. Пожалуйста, предоставьте нам ссылку на авторствоСсылка на статью должна быть гиперссылкой
Например:
Источник: Нижний индекс VBA вне допустимого диапазона (wallstreetmojo.com)
Что такое ошибка нижнего индекса вне диапазона в Excel VBA?
Например, если вы обращаетесь к листу, которого нет в рабочей тетради, то мы получаем Ошибка времени выполнения 9: «Нижний индекс вне диапазона».

Если вы нажмете кнопку «Конец», подпроцедура завершится, если вы нажмете «Отладка», вы перейдете к строке кода, где произошла ошибка, а справка приведет вас на страницу веб-сайта Microsoft.
Почему возникает ошибка Subscript Out of Range?
Как я сказал как врач важно найти покойника, прежде чем думать о лекарстве. Ошибка VBA Subscript out of range возникает, когда строка кода не читает введенный нами объект.
Например, посмотрите на изображение ниже. У меня есть три листа с именами Лист1, Лист2, Лист3.

Теперь в коде я написал код для выбора листа «Продажи».
Код:
Sub Macro2() Sheets("Sales").Select End Sub

Если я запущу этот код с помощью клавиши F5 или вручную, я получу Ошибка времени выполнения 9: «Нижний индекс вне диапазона».

Это потому, что я пытался получить доступ к объекту рабочего листа «Продажи», который не существует в рабочей книге. Это ошибка времени выполнения, поскольку эта ошибка возникла при выполнении кода.
Другая распространенная ошибка нижнего индекса, которую мы получаем, — это когда мы ссылаемся на книгу, которой там нет. Например, посмотрите на приведенный ниже код.
Код:
Sub Macro1() Dim Wb As Workbook Set Wb = Workbooks("Salary Sheet.xlsx") End Sub

Приведенный выше код говорит, что переменная WB должна быть равна рабочей книге «Salary Sheet.xlsx». На данный момент эта книга не открывается на моем компьютере. Если я запущу этот код вручную или через клавишу F5, я получу Ошибка времени выполнения 9: «Нижний индекс вне диапазона».

Это связано с книгой, о которой я говорю, которая либо не открыта, либо вообще не существует.
Ошибка индекса VBA в массивах
Когда вы объявляете массив как динамический массив и не используете слово DIM или РЕДИМ в VBAОператор VBA Redim увеличивает или уменьшает объем памяти, доступный для переменной или массива. Если с этим оператором используется Preserve, создается новый массив другого размера; в противном случае изменяется размер массива текущей переменной.читать далее чтобы определить длину массива, мы обычно получаем ошибку VBA Subscript out of range. Например, посмотрите на приведенный ниже код.
Код:
Sub Macro3() Dim MyArray() As Long MyArray(1) = 25 End Sub

В приведенном выше примере я объявил переменную как массив, но не назначил начальную и конечную точки; скорее, я сразу присвоил первому массиву значение 25.
Если я запущу этот код с помощью клавиши F5 или вручную, мы получим Ошибка времени выполнения 9: «Нижний индекс вне диапазона».

Чтобы решить эту проблему, мне нужно присвоить длину массива с помощью слова Redim.
Код:
Sub Macro3() Dim MyArray() As Long ReDim MyArray(1 To 5) MyArray(1) = 25 End Sub

Этот код не выдает никаких ошибок.
Как показать ошибки в конце кода VBA?
Если вы не хотите видеть ошибку, пока код запущен и работает, но вам нужен список ошибок в конце, вам нужно использовать обработчик ошибок «On Error Resume». Посмотрите на приведенный ниже код.
Код:
Sub Macro1() Dim Wb As Workbook On Error Resume Next Set Wb = Workbooks("Salary Sheet.xlsx") MsgBox Err.Description End Sub

Как мы видели, этот код выдает Ошибка времени выполнения 9: «Нижний индекс вне диапазона в экселе VBA. Но я должен использовать обработчик ошибок При ошибке продолжить дальше в VBAОператор VBA On Error Resume — это аспект обработки ошибок, используемый для игнорирования строки кода, из-за которой возникла ошибка, и продолжения со следующей строки сразу после строки кода с ошибкой.читать далее во время выполнения кода. Никаких сообщений об ошибках мы не получим. Скорее в конце окна сообщения отображается описание ошибки, подобное этому.

Вы можете скачать шаблон подписки Excel VBA вне диапазона здесь: — Подстрочный индекс VBA вне шаблона диапазона
УЗНАТЬ БОЛЬШЕ >>
Post Views: 619
My VB(A) is far away, but still. the (Re)Dim() method defines the size of the array; the index of the array goes from 0 to size-1. Therefore, when you do this :
errorc = 1
If Len(Me.txt_Listnum) = 0 Then
ReDim Preserve myarray(errorc)
myarray(errorc) = "Numer Listy"
errorc = errorc + 1
End If
- You redimension myarray to contain 1 element (
ReDim Preserve myarray(errorc)). it will have only 1 index : 0 - you try to place something in index 1 (
myarray(errorc) = "Numer Listy"), which will fail with the error message you mention.
So what you should to is organize things like this :
errorc = 0
If Len(Me.txt_Listnum) = 0 Then
errorc = errorc + 1 'if we get here, there's 1 error more
ReDim Preserve myarray(errorc) 'extend the array to the number of errors
myarray(errorc-1) = "Numer Listy" 'place the error message in the last index of the array, which you could get using UBound() too
End If
EDIT
Following your remark, I had a look at this page. I’m a bit surprised. From where I see it UBound should return the size of the array -1, but from the examples given it seems it returns the size of the array, point. So, if the examples on that page are correct (and your error seems to indicate they are), you should write your loop this way :
For i = LBound(myarray) To UBound(myarray)-1
msg = msg & myarray(i) & vbNewLine
Next i