What is subscript out of range error in excel

Symptoms

When you use the Location property or Location.Address of vertical or horizontal page breaks in a Microsoft Visual Basic for Applications macro, you may receive the following error message:

Run-time error ‘9’:
Subscript out of range

Cause

This problem may occur if the following conditions are true:

  • The active cell is above the horizontal page break or to the left of the vertical page break that is referred to by the HPageBreaks or VPageBreaks index.

  • The vertical or horizontal page break location is off the screen to the right of the visible window or below the visible window of the workbook.

  • You use a Visual Basic for Applications macro in Microsoft Excel similar to the following code:

    Sub TestHorizontal()
    ActiveSheet.Range("CZ1000").Value = 1
    MsgBox ActiveSheet.HPageBreaks.Count
    MsgBox ActiveSheet.HPageBreaks(1).Location.Address
    MsgBox ActiveSheet.HPageBreaks(2).Location.Address
    End Sub

    Sub TestVertical()
    ActiveSheet.Range("CZ1000").Value = 1
    MsgBox ActiveSheet.VPageBreaks.Count
    MsgBox ActiveSheet.VPageBreaks(1).Location.Address
    MsgBox ActiveSheet.VPageBreaks(2).Location.Address
    MsgBox ActiveSheet.VPageBreaks(3).Location.Address
    End Sub

Workaround

Microsoft provides programming examples for illustration only, without warranty either expressed or implied. This includes, but is not limited to, the implied warranties of merchantability or fitness for a particular purpose. This article assumes that you are familiar with the programming language that is being demonstrated and with the tools that are used to create and to debug procedures. Microsoft support engineers can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific requirements.
To prevent this problem, add code to select the last cell used in the worksheet before the code uses the Location property of horizontal or vertical page breaks. For example, use the following code to select the end cell, use the Location property, and then reselect the original active cell:

Sub CheckPageBreaks()

'Set object "currcell" equal to active cell.
Set currcell = ActiveCell

'Select the last cell on the worksheet that has data.
Range("IV65536").Select

'Include code with Location property here.
x = ActiveSheet.HPageBreaks(2).Location.Address
MsgBox x
'Example sets x equal to address of second horizontal page break.
'Then message box displays the address of the page break.

'Select original active cell.
currcell.Select

End Sub

After the Location property is calculated, you may again select the original active cell. If you use code to scroll between the first and last cell, or select the last cell and immediately reselect the starting cell, the error may still occur. The screen must redraw and the Location property be calculated for the workaround to be effective. If you use the above code with

Application.ScreenUpdating = False

to prevent screen redraw, the problem still occurs.

Status

Microsoft has confirmed that this is a problem in the Microsoft products that are listed in the «Applies to» section.

More Information

If you use the Count method with the VPageBreaks or HPageBreaks property, you may receive a result of zero. This occurs under the conditions listed in the «Cause» section. If a page break is visible, the Count method may give the correct answer. The Count method for vertical or horizontal page breaks may give the expected result if a page break is near the visible part of the workbook window. The workaround given earlier can be used to obtain the expected count.

Page breaks that are to the right of the workbook window or below the workbook window may enable the Count method to work and that page break to be located, if the distance from the window to the page break is less than one-half the distance between page breaks.

References

For more information about how to trap errors in a macro, click the following article number to view the article in the Microsoft Knowledge Base:

213637 How to use «On Error» to handle errors in a macro

Need more help?

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

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

 

tgg

Пользователь

Сообщений: 12
Регистрация: 23.02.2014

Добрый вечер знатоки. Простой макрос стал прерываться ошибка runtime error 9 subscript out of range, долго искал причину.. а оказалось дело в следующем. При открытии другой Книги, или работая в другой книге в момент когда запускаются макросы (2 шт.каждые 60сек) в Книге1 и вылетает error

Изменено: tgg16.03.2018 10:48:28

 

А где собственно вопрос?

С уважением,
Федор/Все_просто

 

tgg

Пользователь

Сообщений: 12
Регистрация: 23.02.2014

#3

27.03.2015 20:31:46

На строке With Worksheets(«Лист1») всё и происходит!
Что надо изменить в коде (?) для работы одновременно в разных Книгах EXCEL

Код
Sub ShowWatch()     
ThisWorkbook.Sheets(1).Range("F1").Value = Now - Date     
Application.OnTime Now + TimeSerial(0, 0, 60), "ShowWatch"     
Application.OnTime Now + TimeSerial(0, 0, 60), "Proverka" 
End Sub 

Private Sub "Proverka"() 
With Worksheets("Лист1")             
If [I2] = "a" Then                 
Exit Sub             
 End If             
If [J2] <> "Ok" Then                 
Exit Sub             
 End If 
OtpravkaPisma     
[I2] = "a"     
[G2] = [D139]     
[G2].Value = [G2].Value         
End With End Sub

Изменено: tgg31.03.2015 22:50:24

 

Казанский

Пользователь

Сообщений: 8839
Регистрация: 11.01.2013

#4

27.03.2015 20:46:12

Начало второй процедуры:

Код
Private Sub Proverka()
With ThisWorkbook.Worksheets("Лист1")
  If .Range("I2") = "a" Then

Аналогично переделайте все квадратные скобки.

 

tgg

Пользователь

Сообщений: 12
Регистрация: 23.02.2014

Вот в чём вопрос??
Пол часа полёт нормальный!
Спасибо огромное, все работает.
Но мучает вопрос, в чем косяк случился?

Изменено: tgg31.03.2015 22:50:35

 

1. Worksheets(«Лист1»)  — без указания принадлежности к книге, относится к активной в момент запуска макроса книге. Видимо, в ней нет листа Лист1.
2. Оператор With фактически не работает, т.к. нигде нет обращения к свойству или методу, начинающегося с точки.
3. [I2], т.е. Range(«I2») — без указания листа, относится к активному в момент запуска макроса листу.

 

tgg

Пользователь

Сообщений: 12
Регистрация: 23.02.2014

Еще раз огромное спасибо!!

 

Юрий М

Модератор

Сообщений: 60353
Регистрация: 14.09.2012

Контакты см. в профиле

tgg, два момента:
1. Свои коды оформляйте соответствующим тегом — посмотрите, как выглядит код у Казанского.
2. Не нужно цитировать всё подряд.

 

tgg

Пользователь

Сообщений: 12
Регистрация: 23.02.2014

#9

19.06.2015 22:03:22

Доброго времени суток! Не прошло и полгода …. Я к Вам с поклоном и вопросом.
Макрос в модуле листа из этой темы (

http://www.planetaexcel.ru/forum/?FID=8&PAGE_NAME=read&TID=30902

), с той лишь разностью, что работает с диапазоном — If Not Intersect(ActiveCell, Range(«E18:E27»)) Is Nothing Then. Вот собственно сам макрос:

Код
Option Explicit 

Private Sub Worksheet_SelectionChange(ByVal Target As Range) 
    If Not Intersect(ActiveCell, Range("E18:E27")) Is Nothing Then 
        Call Module1.Spravka 
    End If 
End Sub 

Но старая песня, опять при открытии другой книги excel этот макрос зачем-то срабатывает и встаёт на 2 строке.
Подскажите пожалуйста, как его поправить!?!
Спасибо!

 

Johny

Пользователь

Сообщений: 2737
Регистрация: 21.12.2012

Когда открывается книга, то она становится активной, и поэтому Ваш диапазон Range(«E18:E27») относится уже к ОТКРЫТОЙ книге.

There is no knowledge that is not power

 

tgg

Пользователь

Сообщений: 12
Регистрация: 23.02.2014

Пробовались разные варианты, это первый вариант макроса, с указанием листа и принадлежности к книге. Но результат всегда был один и тот же.

 

Johny

Пользователь

Сообщений: 2737
Регистрация: 21.12.2012

#12

19.06.2015 22:20:38

Цитата
tgg написал: Пробовались разные варианты

Ну так покажите эти «разные» варианты.

There is no knowledge that is not power

 

tgg

Пользователь

Сообщений: 12
Регистрация: 23.02.2014

Так они ведь не работают как надо!

 

Rjn

Пользователь

Сообщений: 6
Регистрация: 16.03.2018

#14

16.03.2018 09:08:30

Добрый день!
В макросах новичок, второй день разбираюсь.
Подскажите  пожалуйста.
Есть макрос который из одного файла переносит информацию в другой файл.
Другой файл называется «Система прогнозирования свободных остатков_пробный.xlsm»
Если этот файл открыт, то  данные переносятся, если файл закрыт, то данные не переносятся и выходит ошибка subscript out of range
Ниже макрос

Код
Dim sbor As Range

Sub PerenosSbor()
   Dim lStart As Long, lEnd As Long, lLastRow As Long

   Application.ScreenUpdating = False
   Application.EnableEvents = False

  Workbooks("Система прогнозирования свободных остатков_пробный.xlsm").Save

   Application.Wait (Now + TimeValue("0:00:3"))

   '1. Определение первой ячейки с данными в столбце "A".
   'After:=Cells(Rows.Count, "A") указывает, с какой ячейки начать поиск.
   'Если не указывать, то поиск ведётся с ячейки "A1" и первой просматриватся
   'ячейка "A2". Если данные уже есть в ячейке "A1", то результат
   'будет неправильным. Поэтому нужно указать ячейку, с которой начинается поиск.

   lStart = Columns("A").Find(What:="?", After:=Cells(1, "A"), _
       LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, _
       SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Row

   '2. Определение последней ячейки с данными в столбце "A".

   lEnd = Columns("A").Find(What:="?", LookIn:=xlValues, LookAt:=xlPart, _
       SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, _
       MatchCase:=False, SearchFormat:=False).Row

   '3. Выделение диапазона с данными в столбце "A".

  Set sbor = Range("A" & lStart & ":G" & lEnd)

With Workbooks("Система прогнозирования свободных остатков_пробный.xlsm").Worksheets("1.СБОР")
lLastRow = .Cells(.Rows.Count, 1).End(xlUp).Row + 1
On Error Resume Next
.ShowAllData
sbor.Copy
.Range("A" & lLastRow).PasteSpecial xlPasteValuesAndNumberFormats
End With

Workbooks("Система прогнозирования свободных остатков_пробный.xlsm").Save
   Application.ScreenUpdating = True
   Application.EnableEvents = True
End Sub
 

Rjn

Пользователь

Сообщений: 6
Регистрация: 16.03.2018

В чем ошибка???
На сколько я знаю  историю создания макроса, данный макрос так же  писал не профи)

 

Hugo

Пользователь

Сообщений: 23103
Регистрация: 22.12.2012

Ведь естественно — если файл закрыт, то при попытке его сохранения должна быть ошибка.

 

Sanja

Пользователь

Сообщений: 14837
Регистрация: 10.01.2013

#17

16.03.2018 09:19:33

Цитата
Rjn написал: В чем ошибка?

Вы же выше сами написали, что

Цитата
Rjn написал: Если этот файл открыт, то  данные переносятся, если файл закрыт, то данные не переносятся

Макрос написан именно так, что файл должен быть предварительно открыт

Согласие есть продукт при полном непротивлении сторон.

 

Rjn

Пользователь

Сообщений: 6
Регистрация: 16.03.2018

А где и как исправить макрос, что бы он работал при закрытом  файле?

 

vikttur

Пользователь

Сообщений: 47199
Регистрация: 15.09.2012

1. Код в сообщении  следует оформлять кнопкой <…>
2. Не нужно форматировать шрифт мелким. Стандартный нормально смотрится.

 

vsahno

Пользователь

Сообщений: 42
Регистрация: 22.07.2017

#20

21.02.2019 19:08:28

Цитата
tgg написал:
Так они ведь не работают как надо!

У меня не были прописаны ПОЛНЫЕ ИМЕНА ФАЙЛОВ! — только название, без расширения:
Workbooks(«Авторизация»).Worksheets(«Лист8»)
НА моем компе макросы работали как надо! НО при установке у клиента … как там — …»runtime error 9 subscript out of range». Главное у них и по сети на 1 компе все прекрасно работало!!!
Пока додумался до: Workbooks(«Авторизация.xlsm»).Worksheets(«Лист8») —  больше часа убил и вспотел! :)

pasha7598

0 / 0 / 0

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

Сообщений: 9

1

14.03.2020, 12:07. Показов 20623. Ответов 15

Метки vba excel (Все метки)


Добрый день, уважаемые знатоки, обращаюсь к Вам от безысходности. Имеется следующий цикл:

Visual Basic
1
2
3
4
5
6
Do Until Workbooks(НазваниеКниги).Worksheets(НазваниеЛиста).Cells(НомерСтроки, j) = ""
    With Workbooks(НазваниеКниги)
        Worksheets(НовыйЛист).Cells(СтрокаВывод, j) = Worksheets(НазваниеЛиста).Cells(НомерСтроки, j)
    End With
    j = j + 1
    Loop

Весь код работает, но когда дело доходит до него, ругается мол строка «Subscript out of range»:

Visual Basic
1
Worksheets(НовыйЛист).Cells(СтрокаВывод, j) = Worksheets(НазваниеЛиста).Cells(НомерСтроки, j)

Понятия не имею в чем дело, вроде бы всем переменным значения присвоены, берутся они все из формы, куда все предварительно вводится, а ругается еще при первом действии, т.е. цикл по факту не начался.

Вложения

Тип файла: rar Книга1.rar (765.6 Кб, 11 просмотров)

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

0

Модератор

Эксперт функциональных языков программированияЭксперт Python

33805 / 18840 / 3971

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

Сообщений: 31,600

Записей в блоге: 12

14.03.2020, 12:43

2

Эта ошибка может возникнуть, если отсутствует один из листов книги (не только из-за массивов)

0

0 / 0 / 0

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

Сообщений: 9

14.03.2020, 12:46

 [ТС]

3

Да, я прекрасно понимаю, но я клацал debug и смотрел, что вместо переменных все названия листов и книг присутствуют, просто не могу понять в чем проблема

0

Модератор

Эксперт функциональных языков программированияЭксперт Python

33805 / 18840 / 3971

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

Сообщений: 31,600

Записей в блоге: 12

14.03.2020, 12:47

4

А чему равно j?

0

0 / 0 / 0

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

Сообщений: 9

14.03.2020, 12:51

 [ТС]

5

j=1, а все названия предварительно вводятся в форме и в тестбоксы и потом беруться оттуда. Сам уже второй день сижу и туплю, может не замечаю чего-то

0

Модератор

Эксперт MS Access

11261 / 4592 / 739

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

Сообщений: 13,157

Записей в блоге: 4

14.03.2020, 13:25

6

Цитата
Сообщение от pasha7598
Посмотреть сообщение

Workbooks(НазваниеКниги).Worksheets(НазваниеЛиста) .Cells(НомерСтроки, j)

вот и проверьте значения переменные
— явно где то нет значения
— или НомерСтроки<=0 или j<=0

0

aequit

223 / 134 / 45

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

Сообщений: 283

Записей в блоге: 1

14.03.2020, 13:28

7

Цитата
Сообщение от pasha7598
Посмотреть сообщение

Сам уже второй день сижу и туплю, может не замечаю чего-то

здравствуйте!
Просто не надо выделываться и убирать Option Explicit
В результате у Вас полный бардак в переменных.
У меня при попытке запуска Вашего кода ошибка проявилась на строке

Visual Basic
1
If Abs(x - x0) < Отклонение Then

так как в необъявленных переменных находился текст и была попытка произвести с ним вычитание и т. д.
Дальше не смотрел.

1

shanemac51

Модератор

Эксперт MS Access

11261 / 4592 / 739

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

Сообщений: 13,157

Записей в блоге: 4

14.03.2020, 13:35

8

у вас нет в модулях обязательной строки Option Explicit и у вас не проходит компиляция
следовательно невозможно гарантировать выполнение и то, что другой модуль знает это имя

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Private Sub ComboBox1_Change() ' список листов в открытой книге
    Dim Sheet As Worksheet: ComboBox2.Clear
    Dim НазваниеЛиста As String
    For Each Sheet In Workbooks((ComboBox1)).Worksheets
            Me.ComboBox2.AddItem (Sheet.Name)
    Next
    НазваниеЛиста = UserForm1.ComboBox2.Text
End Sub
Private Sub CommandButton1_Click()
    Dim НомерСтроки As Integer
    Dim НомерСтолбца As Integer
    Dim Режим As Single
    Dim Показания As Single
    Dim Точка As Single
    Dim НовыйЛист As String
    Dim СтрокаВывод As Integer
    Dim Отклонение As Single
    НомерСтроки = UserForm1.TextBox4.Value
    НомерСтолбца = UserForm1.TextBox5.Value
    Режим = UserForm1.TextBox2.Value
    Показания = UserForm1.TextBox3.Value
    Точка = Round(Режим / Показания, 0)
    НовыйЛист = UserForm1.TextBox6.Text
    НазваниеКниги = UserForm1.ComboBox1.Text    ''''' неизвестное имя

1

1778 / 1108 / 338

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

Сообщений: 3,911

14.03.2020, 15:24

9

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

Решение

pasha7598, смотрю на строки кода (рар у меня не читается) и думаю, а зачем там оператор With?
Если Worksheets(НовыйЛист) и Worksheets(НазваниеЛиста) находятся оба в Workbooks(НазваниеКниги), то он просто не нужен, а если книги разные, то тогда ясно почему вылетает ошибка, надо перед одним из листов поставить точку.

Добавлено через 2 минуты
Или активной в момент выполнения этого кода является не та книга, которую вы бы хотели

Добавлено через 32 минуты
т.к. оператор Do Until …. проходит, то выведите (или посмотрите в дебугере) до With значение переменной НовыйЛист и всё, думаю, станет ясно.

1

0 / 0 / 0

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

Сообщений: 9

14.03.2020, 21:36

 [ТС]

10

НомерСтроки он точно положителен, ведь он вводится собственноручно с клавиатуры, а j зарание присвоено 1

Добавлено через 1 минуту
Просто в моем случае это определенно будут цифры и текста там оказаться не может никоим образом. Просто задача стоит такая, что нужно выбрать момент выхода установки на стационарный режим, так что возможно у Вас там где-то попался текст

Добавлено через 2 минуты
О боже, да, спасибо, заработало и как я мог забыть, что там нужна точка. Безумно благодарен за помощь.

0

Narimanych

2561 / 1584 / 724

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

Сообщений: 4,955

14.03.2020, 22:01

11

pasha7598,
Попробуйте перед обоими точки :

Visual Basic
1
.Worksheets(НовыйЛист).Cells(СтрокаВывод, j) = .Worksheets(НазваниеЛиста).Cells(НомерСтроки, j)

и здесь…

Visual Basic
1
2
 
.Worksheets(НовыйЛист).Cells(СтрокаВывод+1+ m, v) = .Worksheets(НазваниеЛиста).Cells(НомерСтроки+ 2) + i, v)

1

Модератор

Эксперт MS Access

11261 / 4592 / 739

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

Сообщений: 13,157

Записей в блоге: 4

14.03.2020, 22:36

12

Цитата
Сообщение от pasha7598
Посмотреть сообщение

ведь он вводится собственноручно с клавиатуры

да, номер строки вводится в форме, но не запоминается в public — переменную, так что в основном коде номер неизвестен
когда я вставила Option Explicit во все модули — компиляция не проходит

0

0 / 0 / 0

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

Сообщений: 9

14.03.2020, 23:01

 [ТС]

13

Честно сказать, за это уже не совсем шарю, ибо чему в универе научили, тем и пытаюсь пользоваться, кручусь как могу, чтобы выполнить задачу

0

1778 / 1108 / 338

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

Сообщений: 3,911

15.03.2020, 05:16

14

Цитата
Сообщение от pasha7598
Посмотреть сообщение

чему в универе научили, тем и пытаюсь пользоваться

если будете пользоваться только университетскими знаниями, то ничего хорошего не получится, надо и самостоятельно получать дополнительные знания

Цитата
Сообщение от Narimanych
Посмотреть сообщение

Попробуйте перед обоими точки

если книги разные, то получите снова «Subscript out of range»

0

2561 / 1584 / 724

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

Сообщений: 4,955

15.03.2020, 12:20

15

Цитата
Сообщение от Burk
Посмотреть сообщение

Сообщение от Narimanych
Попробуйте перед обоими точки
если книги разные, то получите снова «Subscript out of range»

Спасибо за просвещение…

В коде у него оба листа прописаны в одной и той же книге.

0

1778 / 1108 / 338

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

Сообщений: 3,911

15.03.2020, 12:48

16

Narimanych, я и написал слово ЕСЛИ и что файл у меня не открылся. И про смену активного листа тоже

Добавлено через 7 минут
И писал это для автора, ваш уровень мне известен

0

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.

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

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

Индекс VBA вне диапазона или, как правило, известен как ошибка времени выполнения 9, возникает, когда мы выбираем такую ​​ячейку, лист или книгу, которые на самом деле не соответствуют диапазону или критериям, определенным в Excel. Как будто мы выбрали диапазон из 100 ячеек или столбца, и мы вызвали значения, хранящиеся в 120 ячейках того же столбца. Это означает, что мы выходим за пределы диапазона, чтобы выбрать и вызвать значения, которые не входят в наши определенные критерии. Когда возникает такая ситуация, мы получаем сообщение «Ошибка выполнения 9» во время компиляции или запуска кода. Сообщение об ошибке VBA Subscript out of Range поможет нам исправить ошибку, связанную с диапазоном, выбранным в Excel.

Пример индекса VBA Excel вне диапазона

Ниже приведены различные примеры VBA Subscript вне диапазона в Excel.

Вы можете скачать этот VBA Subscript вне шаблона Excel здесь — VBA Subscript вне шаблона Excel

Индекс VBA вне диапазона — пример № 1

Сначала рассмотрим простой пример. Для этого нам нужно перейти в окна VBA и добавить новый модуль, выбрав пункт меню «Вставка», как показано ниже.

Мы получим белое пустое окно модуля. Это где мы должны сделать работу кодирования.

Теперь напишите «Подкатегория выполняемой функции», для лучшей практики сохраните имя функции в «Подкатегории», как мы делали здесь для VBA Subscript вне диапазона.

Код:

 Sub Subscript_OutOfRange1 () End Sub 

Здесь, в Excel, у нас есть только один лист с именем «Лист1», как показано ниже.

Но мы напишем код для выбора листа, который даже не добавлен, и посмотрим, что произойдет.

Теперь перейдите в окно VBA и напишите Sheets (2), а затем выберите функцию Select, как показано ниже. Это означает, что мы выбираем последовательность листов 2- й позиции с помощью функции выбора.

Код:

 Sub Subscript_OutOfRange1 () Sheets (2). Выберите End Sub 

Теперь скомпилируйте полный код или сделайте это шаг за шагом, чтобы узнать, какая часть кода является ошибкой. Поскольку у нас есть только одна строка кода, мы можем напрямую запустить код, нажав кнопку воспроизведения под строкой меню. Мы получим сообщение об ошибке « V-Time error 9, Subscript out of range » в VBA, как показано ниже.

Это показывает, что мы пытаемся выбрать тот лист, который не существует. Если мы добавим новый лист или изменим последовательность листов в коде со 2- го на 1- й, то мы можем получить успешный запуск кода. Давайте добавим еще один лист и посмотрим, что произойдет.

Теперь снова запустите код. И поскольку мы не увидели никакой ошибки, это означает, что наш код завершает успешный запуск.

Индекс VBA вне диапазона — пример № 2

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

Код:

 Sub Subscript_OutOfRange2 () End Sub 

Теперь с помощью Worksheet мы активируем Sheet1, как показано ниже.

Код:

 Sub Subscript_OutOfRange2 () Рабочие листы ("Sheet1"). Активировать конечную Sub 

Теперь скомпилируйте полный код и запустите. Мы заметим, что не появилось сообщение об ошибке, что означает, что выполнение кода прошло успешно. Теперь давайте поместим пространство между «Листом 1»

Снова скомпилируйте и запустите код.

Как мы видим выше, даже если наш полный процесс и способ написания кода верны, но мы взяли правильное имя листа как «Лист 1». Который на самом деле не имеет места между «Лист1».

Это показывает, что все еще есть шансы получить ошибку, если не написать или написать правильное имя листа или имя книги.

Индекс VBA вне диапазона — пример № 3

В этом примере мы увидим, как выбор неправильного диапазона массива может создать и показать ошибку времени выполнения 9. Начать снова писать подкатегорию в имени выполняемой функции, как показано ниже.

Код:

 Sub Subscript_OutOfRange3 () End Sub 

Теперь с помощью DIM определите массив любого размера и передайте его в строку или целое число. Что зависит от того, что мы хотим хранить в массиве, числа или текст.

Здесь мы рассмотрели массив 2 × 3 как String, как показано ниже.

Код:

 Sub Subscript_OutOfRange3 () Dim SubArray (2, 3) As Sub String End Sub 

Таким образом, он сформирует таблицу для 2 строк и 3 столбцов, и мы можем хранить любые значения в соответствии с нашими потребностями. Поскольку мы выбрали строку, то мы будем рассматривать текст или алфавиты в нем.

Теперь во второй строке кода выберите созданный массив, но с дополнительным или большим столбцом и назначьте текст как ABC или любой другой текст по вашему выбору. Здесь мы выбрали массив 2 × 5, как показано ниже.

Код:

 Sub Subscript_OutOfRange3 () Dim SubArray (2, 3) As String SubArray (2, 5) = ABC End Sub 

Теперь скомпилируйте и запустите код. Как мы можем видеть на скриншоте ниже, мы получили сообщение об ошибке VBA Subscript of Range в Run-time error 9.

Причина получения этой ошибки заключается в том, что мы выбрали неверный диапазон массива в пределах 2 дополнительных столбцов от 2 × 3 до 2 × 5, что выходит за пределы кода. Теперь, если мы снова выберем правильный диапазон массива как 2 × 3 и посмотрим, что произойдет.

После компиляции и запуска кода. Мы увидим, что не получили никакой ошибки, что означает, что наш код был успешно выполнен.

Плюсы Excel VBA Subscript вне диапазона

  • Индекс VBA вне диапазона позволяет нам узнать, что за ошибка произошла. Так что мы можем конкретно найти решение полученного кода ошибки.
  • Поскольку индекс VBA выходит за пределы диапазона «Ошибка времени выполнения 9», очень полезно знать, какая ошибка произошла в Excel.

То, что нужно запомнить

  • Рекомендуется использовать подкатегорию в имени выполняемой функции с последовательностью кода, чтобы ее было легко отслеживать.
  • Сохраните файл как Macro-Enabled Workbook, чтобы избежать потери написанного кода.
  • Если у вас огромные строки кода, лучше скомпилировать каждую строку кода одну за другой, нажав клавишу F8. Этот метод компилирует каждый шаг кода, чтобы мы могли сразу узнать, какая часть кода действительно имеет ошибку с первого раза.

Рекомендуемые статьи

Это было руководство по Excel VBA Subscript вне диапазона. Здесь мы обсудили причину возникновения ошибки VBA Subscript out of Range (Ошибка времени выполнения 9), а также некоторые практические примеры и загружаемый шаблон Excel. Вы также можете просмотреть наши другие предлагаемые статьи —

  1. Как исправить ошибку VBA 1004?
  2. Понимание ошибок в Excel
  3. Полное руководство по VBA при ошибке
  4. Использование функции IFERROR 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 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

I have a problem in excel Vba when I try to run this code, I have an error of subscript out of range:

Private Sub UserForm_Initialize()
  n_users = Worksheets(Aux).Range("C1").Value

  Debug.Print Worksheets(Aux).Range("B1:B" & n_users).Value

  ListBox1.RowSource = Worksheets(Aux).Range("B1:B" & n_users).Value

  ComboBox1.RowSource = Worksheets(Aux).Range("B1:B" & n_users).Value
  ComboBox2.RowSource = Worksheets(Aux).Range("B1:B" & n_users).Value

End Sub

And Debug.Print works well, so the only problem is in Range(«B1:B» & n_users).Value.

asked Oct 19, 2013 at 15:15

user2898085's user avatar

user2898085user2898085

492 gold badges4 silver badges14 bronze badges

5

If the name of your sheet is «Aux», change each Worksheets(Aux) reference to Worksheets("Aux"). Unless you make Aux a string variable, for example:

Dim Aux As String  
Aux = "YourWorksheetName"
n_users = Worksheets(Aux).Range(C1).Value

you must use quatations around sheet references.

answered Oct 19, 2013 at 16:36

ARich's user avatar

ARichARich

3,2004 gold badges30 silver badges56 bronze badges

1

Firstly, unless you have Aux defined somewhere in the actual code, this will not work. The sheet-name reference must be a string value, not an empty variable (which ARich explains in his answer).

Second, the way in which you are trying to populate the rowsource value is incorrect. The rowsource property of a combobox is set using a string value that references the target range. By this I mean the same string value you would use in an excel formula to reference a cell in another sheet. For instance, if your worksheet is named «Aux» then this would be your code:

ComboBox1.RowSource = "Aux!B1:B" & n_users

I think you can also use named ranges. This link explains it a little.

answered Oct 19, 2013 at 18:13

Ross Brasseaux's user avatar

Ross BrasseauxRoss Brasseaux

3,8411 gold badge27 silver badges46 bronze badges

2

I can’t see how you can get an Error 9 on that line. As others have pointed out repeatedly, the place you’ll get it is if the variable Aux doesn’t have a string value representing the name of a worksheet. That aside, I’m afraid that there is a LOT wrong with that code. See the comments in the below revision of it, which as near as I can figure is what you’re trying to get to:

Private Sub UserForm_Initialize()

  'See below re this.
  aux = "Sheet2"

  'You should always use error handling.
  On Error GoTo ErrorHandler

  'As others have pointed out, THIS is where you'll get a
  'subscript out of range if you don't have "aux" defined previously.
  'I'm also not a fan of NOT using Option Explicit, which
  'would force you to declare exactly what n_users is.
  '(And if you DO have it declared elsewhere, I'm not a fan of using
  'public variables when module level ones will do, or module
  'level ones when local will do.)

  n_users = Worksheets(aux).Range("C1").Value

  'Now, I would assume that C1 contains a value giving the number of
  'rows in the range in column B. However this:

  '*****Debug.Print Worksheets(aux).Range("B1:B" & n_users).Value
   'will only work for the unique case where that value is 1.
   'Why? Because CELLS have values. Multi-cell ranges, as a whole,
   'do not have single values. So let's get rid of that.

  'Have you consulted the online Help (woeful though
  'it is in current versions) about what the RowSource property
  'actually accepts? It is a STRING, which should be the address
  'of the relevant range. So again, unless
  'Range("B1:B" & n_users) is a SINGLE CELL that contains such a string
  '(in which case there's no point having n_users as a variable)
  'this will fail as well when you get to it. Let's get rid of it.
  '****ListBox1.RowSource = Worksheets(aux).Range("B1:B" & n_users).Value

  'I presume that this is just playing around so we'll
  'ignore these for the moment.
  'ComboBox1.RowSource = Worksheets(aux).Range("B1:B" & n_users).Value
  'ComboBox2.RowSource = Worksheets(aux).Range("B1:B" & n_users).Value

  'This should get you what you want. I'm assigning to
  'variables just for clarity; you can skip that if you want.

    Dim l_UsersValue As Long
    Dim s_Address As String
    l_UsersValue = 0
    s_Address = ""

    'Try to get the n_users value and test for validity
    On Error Resume Next
    l_UsersValue = Worksheets(aux).Range("C1").Value
    On Error GoTo ErrorHandler

    l_UsersValue = CLng(l_UsersValue)

    If l_UsersValue < 1 Or l_UsersValue > Worksheets(aux).Rows.Count Then
        Err.Raise vbObjectError + 20000, , "User number range is outside acceptable boundaries. " _
        & "It must be from 1 to the number of rows on the sheet."
    End If

    'Returns the cell address
    s_Address = Worksheets(aux).Range("B1:B" & n_users).Address

    'Add the sheet name to qualify the range address
    s_Address = aux & "!" & s_Address

    'And now that we have a string representing the address, we can assign it.

    ListBox1.RowSource = s_Address

ExitPoint:

   Exit Sub

ErrorHandler:

MsgBox "Error: " & Err.Description

Resume ExitPoint

End Sub

answered Oct 19, 2013 at 20:09

Alan K's user avatar

Alan KAlan K

1,9473 gold badges19 silver badges30 bronze badges

5

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

Sometimes when we write and attempt to run sub-procedures in Excel VBA, Excel VBA returns a message box with the error message “Runtime error 9: Subscript out of range.” 

subscript out of range error

The “Subscript out of range” error happens when we reference a non-existent collection member or a non-existent array element.

By the error, Excel VBA is telling us, “I have not found what you are looking for.”

This tutorial gives examples of specific causes of this error and how to fix it.

Before fixing the “Subscript out of range” error, you must identify its cause.

When you press the Debug button on the error message box, Excel VBA takes you to the statement that caused the error. By examining the line of code, you should be able to tell what caused the error. We outline some of the causes and solutions below. 

Cause #1: Referencing a Non-Existent Item in a Collection

We can only access members of collections within their delimited ranges.

Therefore, attempting to access a collection member outside the defined scope will cause the “Subscription out of range” runtime error. 

Suppose we have only Sheet1 and Sheet2 in our active workbook. 

sheets in the workbook

If we write the following sub-procedure and press F5 to run it:

We get the “Subscript out of range” error:

subscript out of range error

The error occurs because the Sheet3 object is not present in the Sheets collection, which consists of all the worksheets and chart sheets in the active workbook.

Therefore the code is referencing a non-existent entity in the Sheets collection.

How to Fix It

You can fix this error in any of the following ways:

  • Create the non-existent object; in this case, add Sheet3 to the workbook.
  • Check the spelling of the name of the collection member you want to access and ensure it is correct.
  • In the Excel VBA code, refer to an object present in the collection; in this case, you can refer to either Sheet1 or Sheet2. 
  • Use the For Each…Next loop instead of referencing specific collection members. The loop allows us to loop through collection members and repeat particular actions, such as unhiding worksheets.
Also read: Not Enough Memory to Complete This Action in Excel – How to Fix?

Cause #2: Attempting to Access a Closed Workbook

If you try to access a closed workbook, you get the “Subscript out of range” error.

For example, if we have a closed workbook called “Employees” on our computer, running the following sub-procedure will generate the “Subscript out of range” error.

Macro to activate closed workbook

This error is generated because a closed workbook is not part of the collection of workbooks.

All the open workbooks on your computer make up the workbooks collection. 

How to Fix It

You can use any of the following methods to fix the error. 

  • Open the workbook you want to access, then run the sub-procedure.
  • Use the For Each…Next loop to check whether the workbook you wish to access is open. The loop goes through all the available workbooks and matches the name of the workbook you want to access against each open workbook. If a match is found, the workbook is open otherwise; the workbook is closed.

Cause #3: Referencing a Non-existent Array Element 

If you reference a non-existent array element in your code, VBA displays the “Subscript out of range” to indicate something wrong with the code.

For example, the following code refers to an array element 11, which is not in the array declaration. 

incorrect array declaration

When we attempt to run the code, we get the “Subscript out of range” error.

How to Fix It

You can use any of the following techniques to solve the problem:

  • Verify the upper and lower bounds of the array in the array declaration. If the dimensions are different from what you intended, adjust them accordingly.
  • Ensure that you only refer to the array elements in the array declaration.
  • Use LBound and UBound functions to direct the access of redimensioned arrays. The LBound function returns the lower boundary of the array, which can be either 0 or 1. The UBound function returns the upper limit of the array, which is equivalent to the number of items in the array. 
  • If the array dimensions are declared variables, ensure the variable names are spelled correctly. 

Cause #4: Not Specifying the Number of Elements in an Array

If you declare an array but do not specify the number of elements in the array and attempt to access an element in the array,  VBA returns the “Subscript out of range” error.

For example, the following code results in the error:

number of arrays not declared

How to Fix It

  • Explicitly specify the number of elements in the array in the array declaration. 

Cause #5: Misspelling the name of a Workbook

If you misspell the name of the workbook you want to access, Excel VBA will return the “Subscript is out of range error.”

For example, if you want to activate a workbook named “Employees.xlsx,” the following code will not activate the workbook but return an error:

misspelled workbook name

Although the workbook is open, the sub-procedure does not activate it because its name needs to be corrected.

How to Fix It

  • Check the spelling of the workbook’s name in the sub-procedure and ensure it is correct. 

Cause #6: Specifying an Invalid Element

Sometimes when you use the shorthand form of a subscript, you may mistakenly specify an invalid element. 

For example, the shorthand for ActiveSheet.Range(“C3”) is [C3]. If this shorthand form of the subscript refers to an invalid element, you will get the “Subscript is out of range error.”

How to Fix It

Use a valid index or name for the collection. 

This tutorial has given reasons and solutions for the “Subscript out of range” error.  This error happens when we reference a non-existent collection member or a non-existent array element.

Examples of specific causes include 

  • Referencing a worksheet or workbook not present in the collection. 
  • Misspelling object names in the code.
  • Referencing a non-existent array element. 
  • Not specifying the number of elements in the array.
  • Attempting to access a closed workbook.
  • Specifying an invalid element. 

The solutions to the error include using the For Each…Next construct, instead of referencing specific items in the code and specifying the elements in an array. 

We hope you found the tutorial helpful.

Other articles you may also like:

  • Using Application.GetSaveAsFilename in VBA in Excel
  • Using Application.EnableEvents in VBA in Excel
  • SetFocus in Excel VBA – How to Use it?
  • How to Open Excel Files Using VBA
  • #NAME? Error in Excel – How to Fix!
  • #NUM! Error in Excel – How to Fix it?
  • SPILL Error in Excel – How to Fix?

Понравилась статья? Поделить с друзьями:
  • What is subject line in word
  • What is subheading in word
  • What is style set in word
  • What is style in microsoft word
  • What is style guide in word