Subscript out of range access как исправить

This techincal guide is about Subscript out of range access import issue in Microsoft Access. If you are searching for the same, then go through it.

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.

Related Post

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)

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)

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.

Related Access Database

  • subscript out of range access
  • access subscript out of range
  • access subscript out of range error
  • subscript out of range
  • ms access subscript out of range
  • access error subscript out of range
  • subscript out of range access error
  • ms access subscript out of range import error
  • subscript out of range error
  • subscript out of range error access import

Access Database Tags: #how to fix subscript out of range error in access #microsoft access 2016 subscript out of range error #ms access subscript out of range form wizard #subscript out of range access 2013 import excel file #subscript out of range access split database #subscript out of range error in access when exporting to excel #what does subscript out of range mean in vba

  • «
  • Facebook
  • Twitter
  • Pin it
  • »
  • 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

Подстрочный индекс 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 вне допустимого диапазона

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

Что такое ошибка нижнего индекса вне диапазона в Excel VBA?

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

Индекс вне диапазона

Если вы нажмете кнопку «Конец», подпроцедура завершится, если вы нажмете «Отладка», вы перейдете к строке кода, где произошла ошибка, а справка приведет вас на страницу веб-сайта Microsoft.

Почему возникает ошибка Subscript Out of Range?

Как я сказал как врач важно найти покойника, прежде чем думать о лекарстве. Ошибка VBA Subscript out of range возникает, когда строка кода не читает введенный нами объект.

Например, посмотрите на изображение ниже. У меня есть три листа с именами Лист1, Лист2, Лист3.

Субскрипт VBA вне допустимого диапазона, пример 1

Теперь в коде я написал код для выбора листа «Продажи».

Код:

Sub Macro2()

   Sheets("Sales").Select

End Sub

Субскрипт VBA вне допустимого диапазона Пример 1-1

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

Субскрипт VBA вне допустимого диапазона Пример 1-2

Это потому, что я пытался получить доступ к объекту рабочего листа «Продажи», который не существует в рабочей книге. Это ошибка времени выполнения, поскольку эта ошибка возникла при выполнении кода.

Другая распространенная ошибка нижнего индекса, которую мы получаем, — это когда мы ссылаемся на книгу, которой там нет. Например, посмотрите на приведенный ниже код.

Код:

Sub Macro1()

  Dim Wb As Workbook

  Set Wb = Workbooks("Salary Sheet.xlsx")

End Sub

Субскрипт VBA вне допустимого диапазона Пример 1-3

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

Субскрипт VBA вне допустимого диапазона Пример 1-4

Это связано с книгой, о которой я говорю, которая либо не открыта, либо вообще не существует.

Ошибка индекса VBA в массивах

Когда вы объявляете массив как динамический массив и не используете слово DIM или РЕДИМ в VBAОператор VBA Redim увеличивает или уменьшает объем памяти, доступный для переменной или массива. Если с этим оператором используется Preserve, создается новый массив другого размера; в противном случае изменяется размер массива текущей переменной.читать далее чтобы определить длину массива, мы обычно получаем ошибку VBA Subscript out of range. Например, посмотрите на приведенный ниже код.

Код:

Sub Macro3()

   Dim MyArray() As Long

   MyArray(1) = 25

End Sub

Субскрипт VBA вне допустимого диапазона, пример 2

В приведенном выше примере я объявил переменную как массив, но не назначил начальную и конечную точки; скорее, я сразу присвоил первому массиву значение 25.

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

Пример диапазона 2-1

Чтобы решить эту проблему, мне нужно присвоить длину массива с помощью слова Redim.

Код:

Sub Macro3()

   Dim MyArray() As Long
   ReDim MyArray(1 To 5)

   MyArray(1) = 25

End Sub

Пример диапазона 2-2

Этот код не выдает никаких ошибок.

Как показать ошибки в конце кода 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

Вне диапазона Пример 3

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

Субскрипт вне допустимого диапазона Пример 3-1

Вы можете скачать шаблон подписки Excel VBA вне диапазона здесь: — Подстрочный индекс VBA вне шаблона диапазона

УЗНАТЬ БОЛЬШЕ >>

Post Views: 719

Joe4

Joe4

MrExcel MVP, Junior Admin


  • #2

Welcome to the Board!

Importing Excel files into Access can sometimes be a fickle thing, especially if you are importing to an existing Access table, or there are inconsistencies in your data.
Have a look here, and see if any of the situations mentioned here apply to you: Subscript Out of Range error when importing into Access 2007 from — Microsoft Community

Note that when Access imports Excel files, it generally looks at about the first ten records to determine the format of each field. If something changes after that, it could cause problems. Like let’s say that you have a field that looks numeric, but down on line 100, there is an alpha character in there. That will cause problems.

I have spent hours on some of these imports before. As a last resort, I will export the Excel file to a text file format (CSV, tab-delimited, Fixed-Width, etc), and then import that into Access. The advantage there is you control the Date Types for all the fields you are importing, and it tends to work a little better.

  • #3

I have had the same problem. I tried copying all my Excel data and pasting it as values only into a new worksheet and then made it into a table. That still did not work. Then tried it with CSV as well. Kept returning an error that Field 65 does not exist in my table! Went back to my Excel spreadsheet (to the values sheet) and re-sized all my columns. Saved it and tried importing again into Access. Hehe! Only got «Unparsable Record» errors, but still imported all the data. Well Done Microsoft!! LOL!

  • #4

yes I have had this problem on many occasions, as I import daily many csvs
Personally I think that a macro formatting all columns is the way to go and also make sure that column names are the same
However I have only today just discovered that saving as a «Tab Delimited» csv is the way to go
I also have Vba code to delete Import error tables after the import takes place
Regards
Graham

  • #5

yes I have had this problem on many occasions, as I import daily many csvs
Personally I think that a macro formatting all columns is the way to go and also make sure that column names are the same
However I have only today just discovered that saving as a «Tab Delimited» csv is the way to go
I also have Vba code to delete Import error tables after the import takes place
Regards
Graham

Hi there — I just had the same problem and it turned out that I had an Input Mask for my PostCode field in .accdb and the Excel field wasn’t matching the input mask. I removed the input mask and it imported! Hope that helps someone.

  • #6

Whenever I run into an issue, I import the file into Access as a new table, compare field value types and formats to the existing table. This helps me solve for my import issues.

  • #7

Today, for the first time, I received the ‘subscript out of range’ error while performing an import I have been doing every week for over a year now. Out of frustration, I closed & re-opened Access, tried the import again and was successful. Hope this helps some…

  • #8

Today, for the first time, I received the ‘subscript out of range’ error while performing an import I have been doing every week for over a year now. Out of frustration, I closed & re-opened Access, tried the import again and was successful. Hope this helps some…

Worked like a charm. thank you

  • #9

Hi all,

I am getting pretty fed up with all the hassle I am having just trying to import data from Excel 2007 to Access 2007 so I hope that someone is able to help!

All I want to do is import a spreadsheet from excel to access. I have checked that all the fields and headings and content are correct. i have actually imported this data previously but had to remove it and start again. However now when I use the import data from excel button and follow the wizard through it comes up saying ‘subscript out of range’.
For a start I dont even know what this means and Access helpfully doesn’t tell you. How do I find out, fix it and import data that happily went in before??
Help!

Try importing data as its own table then perform append query to the table you want. It worked for me

0 / 0 / 0

Регистрация: 22.01.2017

Сообщений: 4

1

22.01.2017, 16:12. Показов 14861. Ответов 3


Народ, помогите. Пытаюсь создать отчет:

В окне База данных активизируйте вкладку Отчеты. В этом же окне нажмите кнопку Создать. 30. С помощью Мастера отчетов создайте отчет для вывода данных запроса Приказ. В качестве источника данных используйте запрос Приказ. Выберите для отчета все поля. При создании отчета использовать сортировку по полю Фамилия, вид отчета Табличный, стиль Строгий, сохраните под именем Приказ. Закройте отчет.

Выходит ошибка(см. прикреплен. фото)
Так же приложил саму БД

Миниатюры

Ошибка subscript out of range
 

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

22.01.2017, 16:12

3

Эксперт MS Access

26772 / 14451 / 3192

Регистрация: 28.04.2012

Сообщений: 15,782

22.01.2017, 16:52

2

Лучший ответ Сообщение было отмечено Melitant как решение

Решение

Действительно какой-то баг. И откуда ноги растут осталось неясным. Причем без поля Процент все нормально. Что в нем, в этом поле непонятно. Не помог даже импорт в новую чистую БД.

Сделал иначе. Мастером создал отчет без поля Процент. А потом уже добавил поле в конструкторе. Смотрите вложение, отчет Приказ1.



1



0 / 0 / 0

Регистрация: 22.01.2017

Сообщений: 4

22.01.2017, 16:59

 [ТС]

3

Сам тоже не понял так. спасибо!
p.s. тему можно закрывать.



0



Эксперт MS Access

16799 / 6965 / 1551

Регистрация: 21.06.2012

Сообщений: 12,998

22.01.2017, 17:03

4

По всей видимости не «любит»

иногда

Аксесс одинаковые имена таблиц/полей, проектов/панелей инструментов, … . Здесь имя таблицы и поля в ней группа, заменил имя поля группа на группa (а на латинице).

Не по теме:

Ловкость рук и никакого мошенничества (С)



2



subscript out of range error message

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:

  1. Referring to a nonexistent element
  2. Wrong collection member
  3. Unidentified element 
  4. 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

running the code in the vba project editor

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.

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

VBA Subscript Out of Range

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.”

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.

VBA Subcript Out of Range Example 1

Now in the code, we have written the code to select the sheet “Sales.”

Code:

Sub Macro2()

   Sheets("Sales").Select

End Sub

VBA Subcript Out of Range Example 1-1

If we run this code using the F5 key or manually, we will get the Run-time error ‘9’: “Subscript out of range.”

VBA Subcript Out of Range Example 1-2

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

VBA Subcript Out of Range Example 1-3

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.

VBA Subcript Out of Range Example 1-4

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

VBA Subcript Out of Range Example 2

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.”

Range Example 2-1

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

Range Example 2-2

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

Out of Range Example 3

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.

Subcript Out of Range Example 3-1

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

Понравилась статья? Поделить с друзьями:
  • Subprocess exited with error при установке pygame
  • Subprocess exited with error pip install
  • Subprocess dpkg deb fsys tarfile returned error exit status 2
  • Subprocess dpkg deb control returned error exit status 2 cydia
  • Subnautica ошибки новичков