Run time error 9 subscript out of range почему

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

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

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

 

Юрий М

Модератор

Сообщений: 60390
Регистрация: 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

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

Сообщений: 23137
Регистрация: 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») —  больше часа убил и вспотел! :)

Содержание

  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: –

Источник

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

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
Icon Ex Номер ошибки: Ошибка во время выполнения 9
Название ошибки: Subscript out of range
Описание ошибки: Elements of arrays and members of collections can only be accessed within their defined ranges.
Разработчик: Microsoft Corporation
Программное обеспечение: Windows Operating System
Относится к: Windows XP, Vista, 7, 8, 10, 11

Обзор «Subscript out of range»

Как правило, практикующие ПК и сотрудники службы поддержки знают «Subscript out of range» как форму «ошибки во время выполнения». Когда дело доходит до программного обеспечения, как Windows Operating System, инженеры могут использовать различные инструменты, чтобы попытаться сорвать эти ошибки как можно скорее. Ошибки, такие как ошибка 9, иногда удаляются из отчетов, оставляя проблему остается нерешенной в программном обеспечении.

После установки программного обеспечения может появиться сообщение об ошибке «Elements of arrays and members of collections can only be accessed within their defined ranges.». Во время возникновения ошибки 9 конечный пользователь может сообщить о проблеме в Microsoft Corporation. Microsoft Corporation может устранить обнаруженные проблемы, а затем загрузить измененный файл исходного кода, позволяя пользователям обновлять свою версию. Чтобы исправить такие ошибки 9 ошибки, устанавливаемое обновление программного обеспечения будет выпущено от поставщика программного обеспечения.

Почему возникает ошибка времени выполнения 9?

В большинстве случаев вы увидите «Subscript out of range» во время загрузки Windows Operating System. Вот три наиболее распространенные причины, по которым происходят ошибки во время выполнения ошибки 9:

Ошибка 9 Crash — Ошибка 9 может привести к полному замораживанию программы, что не позволяет вам что-либо делать. Если данный ввод недействителен или не соответствует ожидаемому формату, Windows Operating System (или OS) завершается неудачей.

Утечка памяти «Subscript out of range» — если есть утечка памяти в Windows Operating System, это может привести к тому, что ОС будет выглядеть вялой. Есть некоторые потенциальные проблемы, которые могут быть причиной получения проблем во время выполнения, с неправильным кодированием, приводящим к бесконечным циклам.

Ошибка 9 Logic Error — логическая ошибка возникает, когда компьютер производит неправильный вывод, даже если вход правильный. Это видно, когда исходный код Microsoft Corporation включает дефект в анализе входных данных.

Subscript out of range проблемы часто являются результатом отсутствия, удаления или случайного перемещения файла из исходного места установки Windows Operating System. В большинстве случаев скачивание и замена файла Microsoft Corporation позволяет решить проблему. Мы также рекомендуем выполнить сканирование реестра, чтобы очистить все недействительные ссылки на Subscript out of range, которые могут являться причиной ошибки.

Распространенные сообщения об ошибках в Subscript out of range

Обнаруженные проблемы Subscript out of range с Windows Operating System включают:

  • «Ошибка программы Subscript out of range. «
  • «Ошибка программного обеспечения Win32: Subscript out of range»
  • «Subscript out of range столкнулся с проблемой и закроется. «
  • «Subscript out of range не может быть найден. «
  • «Subscript out of range не может быть найден. «
  • «Проблема при запуске приложения: Subscript out of range. «
  • «Файл Subscript out of range не запущен.»
  • «Отказ Subscript out of range.»
  • «Неверный путь к приложению: Subscript out of range.»

Эти сообщения об ошибках Microsoft Corporation могут появляться во время установки программы, в то время как программа, связанная с Subscript out of range (например, Windows Operating System) работает, во время запуска или завершения работы Windows, или даже во время установки операционной системы Windows. Документирование проблем Subscript out of range в Windows Operating System является ключевым для определения причины проблем с электронной Windows и сообщения о них в Microsoft Corporation.

Причины ошибок в файле Subscript out of range

Проблемы Subscript out of range могут быть отнесены к поврежденным или отсутствующим файлам, содержащим ошибки записям реестра, связанным с Subscript out of range, или к вирусам / вредоносному ПО.

Более конкретно, данные ошибки Subscript out of range могут быть вызваны следующими причинами:

  • Поврежденная или недопустимая запись реестра Subscript out of range.
  • Вирус или вредоносное ПО, повреждающее Subscript out of range.
  • Другая программа (не связанная с Windows Operating System) удалила Subscript out of range злонамеренно или по ошибке.
  • Другое приложение, конфликтующее с Subscript out of range или другими общими ссылками.
  • Поврежденная загрузка или неполная установка программного обеспечения Windows Operating System.

Продукт Solvusoft

Загрузка
WinThruster 2022 — Проверьте свой компьютер на наличие ошибок.

Совместима с Windows 2000, XP, Vista, 7, 8, 10 и 11

Установить необязательные продукты — WinThruster (Solvusoft) | Лицензия | Политика защиты личных сведений | Условия | Удаление

В этой статье представлена ошибка с номером Ошибка 9, известная как Индекс вне диапазона, описанная как Доступ к элементам массивов и членам коллекций можно получить только в пределах их определенных диапазонов.

О программе Runtime Ошибка 9

Время выполнения Ошибка 9 происходит, когда Windows дает сбой или падает во время запуска, отсюда и название. Это не обязательно означает, что код был каким-то образом поврежден, просто он не сработал во время выполнения. Такая ошибка появляется на экране в виде раздражающего уведомления, если ее не устранить. Вот симптомы, причины и способы устранения проблемы.

Определения (Бета)

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

  • Массивы . Массив — это упорядоченная структура данных, состоящая из набора значений элементов или переменных, каждый из которых идентифицируется одним одномерным массивом, вектором или несколькими индексами.
  • Коллекции — API коллекций предоставляют разработчикам набор классов и интерфейсов, которые упрощают работу с коллекциями объектов.
  • Определено . Определение — это недвусмысленное определение значения слова или фразы
  • Элементы — Сущности, которые являются отдельными членами более крупного набора, списка, группы ….
  • < li> Диапазон — диапазон — это диапазон значений между его нижней и верхней границей.

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

Симптомы Ошибка 9 — Индекс вне диапазона

Ошибки времени выполнения происходят без предупреждения. Сообщение об ошибке может появиться на экране при любом запуске %программы%. Фактически, сообщение об ошибке или другое диалоговое окно может появляться снова и снова, если не принять меры на ранней стадии.

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

Fix Индекс вне диапазона (Error Ошибка 9)
(Только для примера)

Причины Индекс вне диапазона — Ошибка 9

При разработке программного обеспечения программисты составляют код, предвидя возникновение ошибок. Однако идеальных проектов не бывает, поскольку ошибки можно ожидать даже при самом лучшем дизайне программы. Глюки могут произойти во время выполнения программы, если определенная ошибка не была обнаружена и устранена во время проектирования и тестирования.

Ошибки во время выполнения обычно вызваны несовместимостью программ, запущенных в одно и то же время. Они также могут возникать из-за проблем с памятью, плохого графического драйвера или заражения вирусом. Каким бы ни был случай, проблему необходимо решить немедленно, чтобы избежать дальнейших проблем. Ниже приведены способы устранения ошибки.

Методы исправления

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

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

Обратите внимание: ни ErrorVault.com, ни его авторы не несут ответственности за результаты действий, предпринятых при использовании любого из методов ремонта, перечисленных на этой странице — вы выполняете эти шаги на свой страх и риск.

Метод 3 — Обновите программу защиты от вирусов или загрузите и установите последнюю версию Центра обновления Windows.

Заражение вирусом, вызывающее ошибку выполнения на вашем компьютере, необходимо немедленно предотвратить, поместить в карантин или удалить. Убедитесь, что вы обновили свою антивирусную программу и выполнили тщательное сканирование компьютера или запустите Центр обновления Windows, чтобы получить последние определения вирусов и исправить их.

Метод 1 — Закройте конфликтующие программы

Когда вы получаете ошибку во время выполнения, имейте в виду, что это происходит из-за программ, которые конфликтуют друг с другом. Первое, что вы можете сделать, чтобы решить проблему, — это остановить эти конфликтующие программы.

  • Откройте диспетчер задач, одновременно нажав Ctrl-Alt-Del. Это позволит вам увидеть список запущенных в данный момент программ.
  • Перейдите на вкладку «Процессы» и остановите программы одну за другой, выделив каждую программу и нажав кнопку «Завершить процесс».
  • Вам нужно будет следить за тем, будет ли сообщение об ошибке появляться каждый раз при остановке процесса.
  • Как только вы определите, какая программа вызывает ошибку, вы можете перейти к следующему этапу устранения неполадок, переустановив приложение.

Метод 2 — Обновите / переустановите конфликтующие программы

Использование панели управления

  • В Windows 7 нажмите кнопку «Пуск», затем нажмите «Панель управления», затем «Удалить программу».
  • В Windows 8 нажмите кнопку «Пуск», затем прокрутите вниз и нажмите «Дополнительные настройки», затем нажмите «Панель управления»> «Удалить программу».
  • Для Windows 10 просто введите «Панель управления» в поле поиска и щелкните результат, затем нажмите «Удалить программу».
  • В разделе «Программы и компоненты» щелкните проблемную программу и нажмите «Обновить» или «Удалить».
  • Если вы выбрали обновление, вам просто нужно будет следовать подсказке, чтобы завершить процесс, однако, если вы выбрали «Удалить», вы будете следовать подсказке, чтобы удалить, а затем повторно загрузить или использовать установочный диск приложения для переустановки. программа.

Использование других методов

  • В Windows 7 список всех установленных программ можно найти, нажав кнопку «Пуск» и наведя указатель мыши на список, отображаемый на вкладке. Вы можете увидеть в этом списке утилиту для удаления программы. Вы можете продолжить и удалить с помощью утилит, доступных на этой вкладке.
  • В Windows 10 вы можете нажать «Пуск», затем «Настройка», а затем — «Приложения».
  • Прокрутите вниз, чтобы увидеть список приложений и функций, установленных на вашем компьютере.
  • Щелкните программу, которая вызывает ошибку времени выполнения, затем вы можете удалить ее или щелкнуть Дополнительные параметры, чтобы сбросить приложение.

Метод 4 — Переустановите библиотеки времени выполнения

Вы можете получить сообщение об ошибке из-за обновления, такого как пакет MS Visual C ++, который может быть установлен неправильно или полностью. Что вы можете сделать, так это удалить текущий пакет и установить новую копию.

  • Удалите пакет, выбрав «Программы и компоненты», найдите и выделите распространяемый пакет Microsoft Visual C ++.
  • Нажмите «Удалить» в верхней части списка и, когда это будет сделано, перезагрузите компьютер.
  • Загрузите последний распространяемый пакет от Microsoft и установите его.

Метод 5 — Запустить очистку диска

Вы также можете столкнуться с ошибкой выполнения из-за очень нехватки свободного места на вашем компьютере.

  • Вам следует подумать о резервном копировании файлов и освобождении места на жестком диске.
  • Вы также можете очистить кеш и перезагрузить компьютер.
  • Вы также можете запустить очистку диска, открыть окно проводника и щелкнуть правой кнопкой мыши по основному каталогу (обычно это C :)
  • Щелкните «Свойства», а затем — «Очистка диска».

Метод 6 — Переустановите графический драйвер

Если ошибка связана с плохим графическим драйвером, вы можете сделать следующее:

  • Откройте диспетчер устройств и найдите драйвер видеокарты.
  • Щелкните правой кнопкой мыши драйвер видеокарты, затем нажмите «Удалить», затем перезагрузите компьютер.

Метод 7 — Ошибка выполнения, связанная с IE

Если полученная ошибка связана с Internet Explorer, вы можете сделать следующее:

  1. Сбросьте настройки браузера.
    • В Windows 7 вы можете нажать «Пуск», перейти в «Панель управления» и нажать «Свойства обозревателя» слева. Затем вы можете перейти на вкладку «Дополнительно» и нажать кнопку «Сброс».
    • Для Windows 8 и 10 вы можете нажать «Поиск» и ввести «Свойства обозревателя», затем перейти на вкладку «Дополнительно» и нажать «Сброс».
  2. Отключить отладку скриптов и уведомления об ошибках.
    • В том же окне «Свойства обозревателя» можно перейти на вкладку «Дополнительно» и найти пункт «Отключить отладку сценария».
    • Установите флажок в переключателе.
    • Одновременно снимите флажок «Отображать уведомление о каждой ошибке сценария», затем нажмите «Применить» и «ОК», затем перезагрузите компьютер.

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

Другие языки:

How to fix Error 9 (Subscript out of range) — Elements of arrays and members of collections can only be accessed within their defined ranges.
Wie beheben Fehler 9 (Tiefgestellt außerhalb des zulässigen Bereichs) — Auf Elemente von Arrays und Mitglieder von Sammlungen kann nur innerhalb ihrer definierten Bereiche zugegriffen werden.
Come fissare Errore 9 (Pedice fuori range) — È possibile accedere agli elementi degli array e ai membri delle raccolte solo all’interno degli intervalli definiti.
Hoe maak je Fout 9 (Abonnement buiten bereik) — Elementen van arrays en leden van collecties zijn alleen toegankelijk binnen hun gedefinieerde bereiken.
Comment réparer Erreur 9 (Indice hors limites) — Les éléments des tableaux et les membres des collections ne sont accessibles que dans leurs plages définies.
어떻게 고치는 지 오류 9 (첨자가 범위를 벗어남) — 배열의 요소와 컬렉션의 멤버는 정의된 범위 내에서만 액세스할 수 있습니다.
Como corrigir o Erro 9 (Subscrito fora do intervalo) — Elementos de matrizes e membros de coleções só podem ser acessados ​​dentro de seus intervalos definidos.
Hur man åtgärdar Fel 9 (Prenumeration utanför räckvidd) — Element i matriser och medlemmar i samlingar kan endast nås inom deras definierade intervall.
Jak naprawić Błąd 9 (Indeks dolny poza zakresem) — Dostęp do elementów tablic i członków kolekcji jest możliwy tylko w ich zdefiniowanych zakresach.
Cómo arreglar Error 9 (Subíndice fuera de rango) — Solo se puede acceder a los elementos de matrices y miembros de colecciones dentro de sus rangos definidos.

The Author Об авторе: Фил Харт является участником сообщества Microsoft с 2010 года. С текущим количеством баллов более 100 000 он внес более 3000 ответов на форумах Microsoft Support и создал почти 200 новых справочных статей в Technet Wiki.

Следуйте за нами: Facebook Youtube Twitter

Последнее обновление:

28/11/22 03:56 : Пользователь Windows 10 проголосовал за то, что метод восстановления 3 работает для него.

Рекомендуемый инструмент для ремонта:

Этот инструмент восстановления может устранить такие распространенные проблемы компьютера, как синие экраны, сбои и замораживание, отсутствующие DLL-файлы, а также устранить повреждения от вредоносных программ/вирусов и многое другое путем замены поврежденных и отсутствующих системных файлов.

ШАГ 1:

Нажмите здесь, чтобы скачать и установите средство восстановления Windows.

ШАГ 2:

Нажмите на Start Scan и позвольте ему проанализировать ваше устройство.

ШАГ 3:

Нажмите на Repair All, чтобы устранить все обнаруженные проблемы.

СКАЧАТЬ СЕЙЧАС

Совместимость

Требования

1 Ghz CPU, 512 MB RAM, 40 GB HDD
Эта загрузка предлагает неограниченное бесплатное сканирование ПК с Windows. Полное восстановление системы начинается от $19,95.

ID статьи: ACX010986RU

Применяется к: Windows 10, Windows 8.1, Windows 7, Windows Vista, Windows XP, Windows 2000

subscript out of range error message

When running a VBA procedure, you might receive this error message
“Run-time error ‘9’, Subscript out of range”. In this article, we will talk about the possible reasons for the occurrence of this error and the ways to fix it. 

According to our recent review, there are four categories that can trigger this error:

  1. Referring to a nonexistent element
  2. Wrong collection member
  3. Unidentified element 
  4. Shorthand script

We are going to take a look at each of these categories and show you how to generate this error and share the best way to fix it.

Referring to a nonexistent element

In some cases, you might have referenced an element (a workbook, worksheet, array, etc.) in the code that doesn’t exist. It is also possible that the subscript is either smaller or larger than the range of possible subscripts.

You referred to a nonexistent Worksheet

To generate this error, open the VBA editor and write the following code to select the sheet “customers” in Module1.

Sub Test1()
Sheets("customers").Select
End Sub

running the code in the vba project editor

If you run the code, you will have the error message.

The reason for this error is the fact that there is no sheet named “customers” in the workbook. Our workbook has three sheets named respectively Sheet1, Sheet2 and Sheet3.

To fix the error, create a worksheet named “customers” or rename any of the three existing sheets and run the macro again.

You referred to a Workbook that is not opened on your computer

If you run the code below, you will have the error code because you will be referring to a workbook that is not opened on your computer.

Sub Macro3( B )
Dim Wbk As Workbook
Set Wbk = Workbooks("Employees.xls")
End Sub

Wrong collection member

The subscript may be larger or smaller than the range of possible subscripts. 

To generate this error, run the following code:

Sub Macro( )
Dim PriceArray(5 To 10 ) As Integer
PriceArray(3) = 20
End Sub

Or

Sub Macro( )
Dim PriceArray(5 To 10 ) As Integer
PriceArray(15) = 20
End Sub

The error will be triggered after running any of the two macros above because the PriceArray has been dimensioned from 5 to 10. But the code is referring to a subscript of index 3 (lower than 5) and 15 for the second macro (larger than 10). Elements of arrays and members of collections can only be accessed within their defined ranges.

That is why it is important to check the declaration of the array to verify it’s upper and lower bounds. It is also advisable to use the UBound and LBound functions to condition array accesses if you are working with arrays that are redimensioned.

Unidentified element

You declared an array but didn’t specify the number of elements

The following code will generate the error:

Sub Macro2( )
Dim PriceArray( ) As Integer
PriceArray(5) = 20
End Sub

The error occurs because when declaring the array named PriceArray, the number of elements was not specified. In fact, Visual Basic does not implicitly dimension unspecified array range as 0 to 10.

To avoid the error, you must explicitly specify the number of elements in the array as in the code below:

Sub Macro3( )
Dim PriceArray(0 To 10 ) As Integer
PriceArray(5) = 20

Shorthand script

You might have used a shorthand form of the subscript and it specifies an invalid element. Therefore, it is recommended that you use a valid key name and index for the collection.

For example [A10] is the shorthand for ActiveSheet.Range(A10). This means that instead of writing ActiveSheet.Range(A10).Select you can just write [A1].Select 

If you don’t have a good knowledge of shorthand scripting, avoid using it because it can generate many errors, not just the “Subscript is out of range” error.

The aim of this article was to explain the possible reasons (the list is not exhaustive) for the occurrence of the “Subscript is out of range” error. Through a step by step tutorial, you have been able to fix the error. We hope it has been useful.

Понравилась статья? Поделить с друзьями:
  • Run time error 9 subscript out of range vba как исправить
  • Run keyword and expect error
  • Run time error 9 excel subscript out of range как исправить
  • Run time error 8002 invalid port number windows 7
  • Run time error 76 path not found как исправить excel