Run time error 9 vba excel subscript out of range

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

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
 

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

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

 

Юрий М

Модератор

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

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

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

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

 

Sanja

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

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

 

Дмитрий Минин

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

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

#21

21.03.2023 10:15:59

Добрый день!
Подскажите, как исправить ошибку, мозгов не хватает понять и разобраться?!

Код
Sub GetCoordinates()
    Dim fso As Object
    Dim objShell As Object
    Dim objFolder As Object
    Dim objFile As Object
    Dim strPath As String
    Dim arrDetails As Variant
    Dim latRef As String, lonRef As String
    Dim latDeg As Double, latMin As Double, latSec As Double, lonDeg As Double, lonMin As Double, lonSec As Double, alt As Double
    Dim i As Integer
    
    'Путь к файлу
    strPath = "C:UsersMininDODesktopExifTool-54_[10].JPG"
    
    'Создание объектов
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set objShell = CreateObject("Shell.Application")
    Set objFolder = objShell.Namespace(fso.GetParentFolderName(strPath))
    Set objFile = objFolder.ParseName(fso.GetFileName(strPath))
    
    'Получение деталей файла
    arrDetails = Split(objFolder.GetDetailsOf(objFile, 27), ";")
    
    'Извлечение координат
    For i = 0 To UBound(arrDetails)
        If InStr(arrDetails(i), "GPS Latitude Ref") > 0 Then
            latRef = arrDetails(i + 1)
        ElseIf InStr(arrDetails(i), "GPS Latitude") > 0 Then
            latDeg = CDbl(Split(arrDetails(i + 1), "°")(0))
            latMin = CDbl(Split(arrDetails(i + 1), "°")(1))
            latSec = CDbl(Split(Split(arrDetails(i + 1), "°")(2), ".")(0))
        ElseIf InStr(arrDetails(i), "GPS Longitude Ref") > 0 Then
            lonRef = arrDetails(i + 1)
        ElseIf InStr(arrDetails(i), "GPS Longitude") > 0 Then
            lonDeg = CDbl(Split(arrDetails(i + 1), "°")(0))
            lonMin = CDbl(Split(arrDetails(i + 1), "°")(1))
            lonSec = CDbl(Split(Split(arrDetails(i + 1), "°")(2), ".")(0))
        ElseIf InStr(arrDetails(i), "GPS Altitude") > 0 Then
            alt = CDbl(Replace(arrDetails(i + 1), " m", ""))
        End If
    Next i
    
    'Преобразование координат в десятичные градусы
    If latRef = "S" Then
        latDeg = -latDeg
    End If
    If lonRef = "W" Then
        lonDeg = -lonDeg
    End If
    latDeg = latDeg + (latMin / 60) + (latSec / 3600)
    lonDeg = lonDeg + (lonMin / 60) + (lonSec / 3600)
    
    'Вывод координат в ячейки Excel
    Sheets("Sheet1").Range("A1").Value = latDeg
    Sheets("Sheet1").Range("B1").Value = lonDeg
    Sheets("Sheet1").Range("C1").Value = alt
    
    'Очистка объектов
    Set fso = Nothing
    Set objShell = Nothing
    Set objFolder = Nothing
    Set objFile = Nothing
End Sub

Прикрепленные файлы

  • Безымянный.jpg (228.87 КБ)

 

Существует ли лист «Sheet1» в активной книге?

 

Дмитрий Минин

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

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

#23

21.03.2023 11:00:04

Цитата
написал:
Существует ли лист «Sheet1» в активной книге?

Понял ошибку и уже исправил.

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,2305 gold badges31 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,8511 gold badge27 silver badges47 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

Summary: The runtime error 9 in Excel usually occurs when you use different objects in a code or the object you are trying to use is not defined. This post will discuss the reasons behind the Excel VBA error «Subscript out of Range” and the solutions to resolve the issue. It will also mention an Excel repair tool that can help fix the error if it occurs due to corruption in worksheet.

Free Download for Windows

Contents

  • Causes of VBA Runtime Error 9: Subscript Out Of Range
  • Methods to Fix Excel VBA Error ‘Subscript out of Range’
  • Conclusion

Many users have reported encountering the error “Subscript out of range” (runtime error 9) when using VBA code in Excel. The error often occurs when the object you are referring to in a code is not available, deleted, or not defined earlier. Sometimes, it occurs if you have declared an array in code but forgot to specify the DIM or ReDIM statement to define the length of array.

Causes of VBA Runtime Error 9: Subscript Out Of Range

The error ‘Subscript out of range’ in Excel can occur due to several reasons, such as:

  • Object you are trying to use in the VBA code is not defined earlier or is deleted.
  • Entered a wrong declaration syntax of the array.
  • Wrong spelling of the variable name.
  • Referenced a wrong array element.
  • Entered incorrect name of the worksheet you are trying to refer.
  • Worksheet you trying to call in the code is not available.
  • Specified an invalid element.
  • Not specified the number of elements in an array.
  • Workbook in which you trying to use VBA is corrupted.

Methods to Fix Excel VBA Error ‘Subscript out of Range’

Following are some workarounds you can try to fix the runtime error 9 in Excel.

Method 1: Check the Name of Worksheet in the Code

Sometimes, Excel throws the runtime error 9: Subscript out of range if the name of the worksheet is not defined correctly in the code. For example – When trying to copy content from one Excel sheet (emp) to another sheet (emp2) via VBA code, you have mistakenly mentioned wrong name of the worksheet (see the below code).

Private Sub CommandButton1_Click()
Worksheets("emp").Range("A1:E5").Select
Selection.Copy
Worksheets("emp3").Activate
Worksheets("emp3").Range("A1:E5").Select
ActiveSheet.Paste
Application.CutCopyMode = False
End Sub

VBA Error Subscript Out Of Range-When Incorrect Name

When you run the above code, the Excel will throw the Subscript out of range error.

So, check the name of the worksheet and correct it. Here are the steps:

  • Go to the Design tab in the Developer section.
  • Double-click on the Command button.
  • Check and modify the worksheet name (e.g. from “emp” to “emp2”).

Modified Code From emp to emp2

  • Now run the code.
  • The content in ‘emp’ worksheet will be copied to ‘emp2’ (see below).

Content Copied From emp to emp2

Method 2: Check the Range of the Array

The VBA error “Subscript out of range” also occurs if you have declared an array in a code but didn’t specify the number of elements. For example – If you have declared an array and forgot to declare the array variable with elements, you will get the error (see below):

Runtime Error 9 When Not Declared Array

To fix this, specify the array variable:

Sub FillArray()
Dim curExpense(364) As Currency
Dim intI As Integer
For intI = 0 to 364
curExpense(intI) = 20
Next
End Sub

Method 3: Change Macro Security Settings

The Runtime error 9: Subscript out of range can also occur if there is an issue with the macros or macros are disabled in the Macro Security Settings. In such a case, you can check and change the macro settings. Follow these steps:

  • Open your Microsoft Excel.
  • Navigate to File > Options > Trust Center.
  • Under Trust Center, select Trust Center Settings.
  • Click Macro Settings, select Enable all macros, and then click OK.

Macro Settings In Trust Center

Method 4: Repair your Excel File

The name or format of the Excel file or name of the objects may get changed due to corruption in the file. When the objects are not identified in a VBA code, you may encounter the Subscript out of range error. You can use the Open and Repair utility in Excel to repair the corrupted file. To use this utility, follow these steps:

  • In your MS Excel, click File > Open.
  • Browse to the location where the affected file is stored.
  • In the Open dialog box, select the corrupted workbook.
  • In the Open dropdown, click on Open and Repair.
  • You will see a prompt asking you to repair the file or extract data from it.
  • Click on the Repair option to extract the data as much as possible. If Repair button fails, then click Extract button to recover data without formulas and values.

If the “Open and Repair” utility fails to repair the corrupted/damaged macro-enabled Excel file, then try an advanced Excel repair tool, such as Stellar Repair for Excel. It can easily repair severely corrupted Excel workbook and recover all the items, including macros, cell comments, table, charts, etc. with 100% integrity. The tool is compatible with all versions of Microsoft Excel.

Conclusion

You may experience the “Subscript out of range” error while using VBA in Excel. You can follow the workarounds discussed in this blog to fix the error. If the Excel file is corrupt, then you can use Stellar Repair for Excel to repair the file. It’s a powerful software that can help fix all the issues that occur due to corruption in the Excel file. It helps to recover all the data from the corrupt Excel files (.xls, .xlsx, .xltm, .xltx, and .xlsm) without changing the original formatting. The tool supports Excel 2021, 2019, 2016, and older versions.

About The Author

monika

Monika Dadool is a Technical content writer at Stellar who writes about QuickBooks, Sage50, MySQL Database, Active Directory, e-mail recovery, Microsoft365, Pattern Recognition, and Machine learning. She loves researching, exploring new technology, and Developing engaging technical blogs that help organizations or Database Administrators fix multiple issues. When she isn’t creating content, she is busy on social media platforms, watching web series, reading books, and searching for food recipes.

Best Selling Products

Stellar Repair for Excel

Stellar Repair for Excel

Stellar Repair for Excel software provid

Read More

Stellar Toolkit for File Repair

Stellar Toolkit for File Repair

Microsoft office file repair toolkit to

Read More

Stellar Repair for QuickBooks ® Software

Stellar Repair for QuickBooks ® Software

The most advanced tool to repair severel

Read More

Stellar Repair for Access

Stellar Repair for Access

Powerful tool, widely trusted by users &

Read More

Like this post? Please share to your friends:
  • Run time error 76 path not found word как исправить
  • Run time error 53 file not found mathpage wll word как исправить
  • Run time error 462 vba excel
  • Run time error 438 vba excel как исправить
  • Run time error 424 vba excel object required как исправить