Меню

Subscript out of range vba excel ошибка

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 you 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

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

More on VBA Errors

Type Mismatch (Error 13) | Runtime (Error 1004) | Object Required (Error 424) | Out of Memory (Error 7) | Object Doesn’t Support this Property or Method (Error 438) | Invalid Procedure Call Or Argument (Error 5) | Overflow (Error 6) | Automation error (Error 440) | VBA Error 400

Содержание

  1. Индекс выходит за пределы допустимого диапазона (ошибка 9)
  2. Поддержка и обратная связь
  3. Subscript out of range (Error 9)
  4. Support and feedback
  5. VBA Subscript Out of Range Runtime Error (Error 9)
  6. Subscript Out of Range (Run time: Error 9)
  7. Subscript Out of Range
  8. How Do I Fix Subscript Out of Range in Excel?
  9. VBA Subscript Out of Range
  10. Excel VBA Subscript Out of Range
  11. What is Subscript out of Range Error in Excel VBA?
  12. Why Does Subscript Out of Range Error Occur?
  13. VBA Subscript Error in Arrays
  14. How to Show Errors at the End of the VBA Code?
  15. Recommended Articles

Индекс выходит за пределы допустимого диапазона (ошибка 9)

К элементам массива и коллекции можно обращаться только в пределах их допустимых диапазонов. Эта ошибка имеет следующие причины и способы решения:

Вы обратились к несуществующему элементу массива. Возможно, заданный индекс выходит за пределы диапазона допустимых индексов или размеры массива не соответствуют параметрам, присвоенным на данном этапе приложения. Проверьте верхнюю и нижнюю границы, заданные при объявлении массива. Используйте функции UBound и LBound, чтобы обуславливать доступ к массивам, если вы работаете с массивами, которые имеют другие измерения. Если индекс указан как переменная, проверьте правильность имени переменной.

Массив был объявлен без определения числа элементов. Например, ниже показано сообщение об ошибке, полученное при запуске такого кода:

Visual Basic неявно измеряет неопределенные диапазоны массивов как 0 — 10. Вместо этого необходимо использовать Dim или ReDim, чтобы явно указать число элементов в массиве.

Вы обратились к несуществующему элементу коллекции. Вместо указания индексов попробуйте обработать элементы массива с помощью конструкции For Each. Next.

Вы использовали сокращенную форму индекса, который неявно указывал недопустимый элемент. Например, если вы используете ! оператор с коллекцией — ! неявно указывает ключ. Например, объект!ключевоеИмя. значение эквивалентно объекту. элемент (ключевоеИмя). значение. В этом случае возникает ошибка, если ключевоеИмя обозначает недопустимый ключ в коллекции. Чтобы исправить ошибку, используйте правильное имя ключа или индекс для коллекции.

Для получения дополнительной информации выберите необходимый элемент и нажмите клавишу F1 (для Windows) или HELP (для Macintosh).

Хотите создавать решения, которые расширяют возможности Office на разнообразных платформах? Ознакомьтесь с новой моделью надстроек Office. Надстройки Office занимают меньше места по сравнению с надстройками и решениями VSTO, и вы можете создавать их, используя практически любую технологию веб-программирования, например HTML5, JavaScript, CSS3 и XML.

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

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:

Visual Basic doesn’t implicitly dimension unspecified array ranges as 0 — 10. Instead, you must use Dim or ReDim to specify explicitly the number of elements in an array.

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.

Источник

VBA Subscript Out of Range Runtime Error (Error 9)

Subscript Out of Range (Run time: 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.

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.

Источник

VBA Subscript Out of Range

Excel VBA Subscript Out of Range

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 coding VBA Coding VBA 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 code Error Of Your VBA Code VBA 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

You are free to use this image on your website, templates, etc., Please provide us with an attribution link How to Provide Attribution? Article 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:

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:

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 VBA REDIM In VBA The 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:

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:

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:

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 VBA On Error Resume Next In VBA VBA 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: –

Источник

Подстрочный индекс 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: 624

VBA Subscript out of Range

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.

VBA Subscript out of Range Example 1-1

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

VBA Subscript out of Range Example 1-2

Here in excel, we have only one sheet named as “Sheet1” as shown below.

VBA Subscript out of Range Example 1-3

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

VBA Subscript out of Range Example 1-4

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.

Result of Example 1-5

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.

VBA Subscript out of Range Example 1-6

Now again run the code. And as we did not see any error, which means our code completes the successful run.

Result of Example 1-7

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

VBA Subscript out of Range Example 2-1

Now with the help of Worksheet, we will activate Sheet1 as shown below.

Code:

Sub Subscript_OutOfRange2()

  Worksheets("Sheet1").Activate

End Sub

VBA Subscript out of Range Example 2-2

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”

VBA Subscript out of Range Example 2-3

Again compile and run the code.

Result of Example 2-4

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

VBA Subscript out of Range Example 3-1

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

VBA Subscript out of Range Example 3-2

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

VBA Subscript out of Range Example 3-3

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.

Result of Example 3-4

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.

Result of Example 3-5

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 –

  1. VBA IsError
  2. VBA Get Cell Value
  3. VBA On Error
  4. VBA XML

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Subquery in from must have an alias ошибка
  • Subnautica ошибка при установке