×

VBA Subscript out of Range

What is Subscript out of Range?

The VBA Subscript out of Range error (which is also called as Run-Time Error 9) mostly triggers when the user selects any cell, sheet, or workbook which does not exist does or it exceeds the range or criteria defined by the user in VBA Excel. The index for the window should be the same as the name of the workbook displayed in the title bar of Excel.

For example, you have selected a range of 50 cells of a column in your Excel sheet and have stored the values till 90 cells. In this case, as the values are out of range, VBA will throw a VBA subscript out of range or “Run-Time Error 9” while running the code.

VBA Subscript out of Range

Reasons for its occurrence

Most of the time the Subscript out of Range error triggers because of the following reasons:

  1. Invalid Collection: It occurs when the user attempts to refer an Index for an invalid collection. 
  2. Undefined Object: The object if not read by the line of code that we entered in our VBA code.
  3. Array out of Bound: The referenced array element does not exist or the referred subscript is larger or smaller than the specified range of possible subscripts, or the dimensions of the array are not assigned property.
  4. Undefined Array Elements: The user has not specified the number of elements for the declared array. For example, refer the below code which will generate Subscript out of range error:

Code:

Dim ArrayError() As Integer

MyArry(18) = 2134 ' This will generate Error 9.

  • Shorthand Script: If the user implicitly specifies an invalid element, unlike the shorthand form of the subscript. For example, when the ‘!’ operator is used with a collection, the ‘!’ operator implicitly specifies a key. 

Advantages of Subscript out of Range

  1. VBA Subscript out of Range or “Run-Time Error 9” alerts the user about the positioning of the mistake where it occurred in the VBA code.
  2. It helps the user to specify the kind of error so as they can check it and debug it find the solution of the obtained error code.

Subscript out of Range Example 1

Code:

Sub SubscriptOutOfRange_Example1()
'using the Sheet object refer to your sheet name
'with select method will sselect the mentioned sheet.
Sheets ("SheetN")
End Sub 

Let’s us analyze step-step the above VBA code:

Step 1: Open the developer window by using the shortcut keywords Alt +F11.

Step 2: Create a module by right-clicking on the VBA Project-> Click on Insert-> Click on Module.

VBA Subscript out of Range

Step 3: In the Module window, introduce the sub-block, followed by your macro name.

VBA Subscript out of Range

Step 4: With the help of your Sheets object, specify your sheet name. Here we have mentioned “SheetN” which is not present in Excel.

VBA Subscript out of Range

Sheet 5: We will use the Select method we will select the specified sheet.

VBA Subscript out of Range

Output

Step 6: Execute the above code either by pressing the F5 shortcut key or by clicking on the Run button.

Step 7: You will notice that the Excel VBA will throw a runtime error dialogue box stating: run-time error ‘9’: Subscript out of range".

VBA Subscript out of Range

The reason for the above error is because in the above example we tried to access the sheet object “SheetN” which do not exist in Excel workbook. The VBA macro code will throw a run-time error because this error occurred while running the code.

Debug

Step 8: In the Microsoft Visual Basic dialogue box, click on the Debug option.

VBA Subscript out of Range

Step 9: The VBA will highlight the code consisting of the mismatch error.

VBA Subscript out of Range

Step 10: Resolve the error (type a valid sheet name, unlike Sheet1) and again run the program.

VBA Subscript out of Range

Step 11: The program will run successfully.

Subscript out of Range Example 2 (with Arrays)

When you declare a dynamic array, we use a Dim or REDIM keyword to define the length. What if you don’t mention the keyword Dim or REDIM to set the length of an array. In this case, the VBA macro code will throw the Subscript out of Range error.

Code:

Sub SubscriptOutOfRange_Example2()
'declaring the array object
Dim MyArry() As Integer
MyArry(1) = 25
End Sub 

Let’s us analyze step-step the above VBA code:

Step 1: Open the developer window by using the shortcut keywords Alt +F11.

Step 2: Create a module by right-clicking on the VBA Project-> Click on Insert-> Click on Module.

VBA Subscript out of Range

Step 3: In the Module window, introduce the sub-block, followed by your macro name.

VBA Subscript out of Range

Step 4: Declare your array object.  In the below example, we have not declared the upper and lower bound array points.

VBA Subscript out of Range

Step 5: Assigning a value to the array variable.

VBA Subscript out of Range

Output

Step 6: Execute the above code either by pressing the F5 shortcut key or by clicking on the Run button.

Step 7: You will notice that the Excel VBA will throw a runtime error dialogue box stating: run-time error ‘9’: Subscript out of range".

VBA Subscript out of Range

 The reason for this error is because, in the above example, we have declared the variable as an array, but we have not assigned the upper and lower bound for the array object and have directly assigned the array value.

So, to prevent the Subscript out of Range error with Array’s always cross-check the spelling of the make sure to verify the starting and ending points (or upper bound or lower bound) after declaring an array and cross check the spelling for the index variable.  Or if you are working with dynamic arrays and have been using ReDim(redimensioned) function, make sure to use the LBound (), and UBound () functions to condition accesses.

Debug

Step 8: In the Microsoft Visual Basic dialogue box, click on the Debug option.

VBA Subscript out of Range

Step 9: The VBA will highlight the code consisting of the mismatch error. Here you will notice, it has highlighted the array object. It means you have some issues with its declaration. So, we need to fix and declare the array object properly.

VBA Subscript out of Range

Step 10: After correcting it, run the program again.

Code:

Sub SubscriptOutOfRange_Example2()
'declaring the array object
Dim MyArry(3) As Integer
MyArry(1) = 25
'displaying the MyArray object
MsgBox (MyArry(1))
End Sub 
VBA Subscript out of Range

Code 11: It will successfully run the VBA code, and will give the following result.

VBA Subscript out of Range

Related Topics

Excel VBA DatePart Function

The DatePart function in VBA returns a part (day, month, week, etc.) for the specified date and/or time. Syntax DatePart (Interval, Date, [FirstDayOfWeek], [FirstWeekOfYear]) Parameter Interval (required) – This parameter represents a string specifying the interval to be used. It can...

2 minutes read.

VBA ActiveCell Property

What is the ActiveCell Property? The active cell signifies the active selected cell in the current worksheet. The Active property acts as a reference point and is used to move the cell cursor...

5 minutes read.

Steps to Create a Pivot Table

Steps to Create a Pivot Table: Pivot Tables can be easily automated through VBA coding. To create a Pivot Table in VBA, follow the below step by step procedure to...

4 minutes read.

Excel VBA Array Function

VBA Array Function: The Array function in VBA generates an array containing the given set of values. Syntax Array (Arglist) Parameter Arglist (required) – This parameter the list of values that you want to make...

2 minutes read.

Excel VBA String Function

The String function in VBA creates a String, consisting of several repeated characters. Syntax String (Number, Character) Parameter Number (required) – This parameter represents the number of characters in the returned String. Character (required) – This parameter...

1 minute read.

Excel VBA IsError Function

VBA IsError Function: The IsError function in VBA returns a Boolean value showing whether the specified Expression represents an error or not. Syntax IsError (Expression) Parameter Expression (required)- This parameter represents the variant that you...

1 minute read.

Excel VBA Array

Introduction to VBA Array An array is a type of variable that holds more than one piece of data. In VBA, you can refer to a specific variable (element) of an array by using...

5 minutes read.

Excel VBA DateDiff Function

The DateDiff function in VBA returns a Long data value representing the number of intervals between two specified dates/times where the type of interval is supplied by the user. Syntax DateDiff (Interval, Date1, Date2, [FirstDayOfWeek], [FirstWeekOfYear]) Parameter Interval (required)...

2 minutes read.

VBA ListBox

What is a ListBox? ListBox refers to a permanently displayed control (usually box-shaped) which contains a list of objects (or attribute, or elements) from which the user can select single or multiple attributes....

8 minutes read.

CodeIgniter File Uploading Class

The Codeigniter provides a file Uploading library class which is used to upload any file such as images, pdf, mp3, etc. to the codeigniter’s application. It also allows to set various preferences such...

5 minutes read.

VBA Regex

What is a Regex? Regex stands for Regular Expression is basically a pattern matching strings within another string. They are supported in many languages, including .net, C++, Python, etc. They are...

5 minutes read.

UserForm and its Properties Excel VBA

UserForm and its Properties Userform has certain properties that can be viewed as category wise (based on appearance, behavior, font) or in an alphabetic manner. The property window is used to set or...

11 minutes read.

Excel VBA LBound Function

Excel VBA LBound Function: The LBound function in VBA returns the lowest subscript for the specified dimension in the given array. Syntax LBound (ArrayName, [Dimension]) Parameter ArrayName (required) – This parameter represents an array for which...

1 minute read.

Excel VBA StrComp Function

VBA StrComp Function: The StrComp function in VBA compares two strings and returns an integer value displaying the result of the comparison. Syntax StrComp (String1, String2, [Compare]) Parameter String1 (required)- This parameter represents the first string to...

2 minutes read.

VBA Screen Updating

What is VBA Screen Updating property? Screen Updating is a VBA property which is used to display the output generation while running the code. If this property is enabled, we could see...

6 minutes read.

Excel VBA Space Function

VBA Space Function: The Space function in VBA creates a String consisting of a specified number of spaces. Syntax Space (Number) Parameter Number (required) - This parameter represents the number of spaces. Return This function returns a...

1 minute read.

VBA Pivot Table Grouping

VBA- Pivot Table Grouping For an instance, if in our pivot table, we have 11 different age groups from 20 to 30 -  but there might be a possibility that we...

2 minutes read.

Excel VBA Atn Function

VBA Atn Function: The Atn function in VBA returns the arctangent between quadrant -?/2 and +?/2 for the specified number, in radians. Syntax Atn (Number) Parameter Number (required) – This parameter represents the number that...

1 minute read.

VBA Regex Pattern Validation

VBA Regex Pattern Validation The key purpose of using Regex in VBA was to validate the data and extract the same category of data. There are certain formats that are standard...

6 minutes read.

Excel VBA UBound Function

Excel VBA UBound Function: The UBound function in VBA returns the highest subscript for the specified dimension in the given array. Syntax UBound (ArrayName, [Dimension]) Parameter ArrayName (required) – This parameter represents an array for which...

1 minute read.