×

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

If ElseIf ElseIf Statement or Nested If statement in VBA

VBA Excel: If … ElseIf … ElseIf Statement or Nested If statement This function enables you to check multiple conditions and, based on that, then run one of the statement blocks present. If...

2 minutes read.

Excel VBA Format Function

VBA Format Function The format function in VBA applies a specified format to an expression and returns the result as a string. Syntax Format (Expression, [Format], [FirstDayOfWeek] , [FirstWeekOfYear] ) Parameter Expression (required)- This parameter represents the expression that you want to format. Format...

3 minutes read.

Excel VBA Now Function

Excel VBA Now Function: The Now function in VBA returns the current date and time.  Syntax Now () Parameter NA Return This function returns the current date and time.  Example 1 Sub NowFunction_Example1() 'It will return...

1 minute read.

Excel VBA : With End-with Constructs

With End-with Constructs The With-End With construct enables the user to perform multiple operations on a single object. If you are going to perform several different actions on the same object and typing the same...

4 minutes read.

Excel VBA InStrRev Function

VBA InStrRev Function: The InStrRev function in Excel VBA returns an integer representing the position of a substring within the specified string if the substring is fount else it returns...

2 minutes read.

VBA Not Equal Operator

What is VBA Not Equal Operator? VBA Not Equal binary operator (“<>”) is a logical function that is used to check if the specified values are not equal or not. This...

5 minutes read.

Excel VBA: DO WHILE….Loop

DO WHILE….Loop The “Do While” Loop is the same, unlike the FOR statement, just that it will keep on looping till the specified condition is true. It is used when we want to...

3 minutes read.

Excel VBA Replace Function

VBA Replace Function: The Replace function in VBA searches for a substring within the specified string and replaces its occurrences with a second substring. Syntax Replace (Expression, Find, Replace, [Start], [Count], [Compare]) Parameter Expression (required) – This parameter represents...

2 minutes read.

Excel VBA Right Function

VBA Right Function: The Right function in VBA returns a substring from the end of the given string. Syntax Right (Str, Length) Parameter Str (required) – This parameter represents the string from which you want to...

1 minute read.

Excel VBA CCur Function

The CCur function in VBA is used to convert an expression into a Currency data type. It can take a maximum of 15 digits to the left of the decimal place and...

1 minute read.

Excel VBA IsObject Function

VBA IsObject Function: The IsObject function in VBA returns a Boolean value showing whether the specified variable represents an Object variable type or not. Syntax IsObject (Expression) Parameter Expression (required)- This parameter represents the...

1 minute read.

Excel VBA CInt Function

VBA CInt Function: The VBA Cint function converts the specified expression into an Integer. Syntax Cint (Expression) Parameter Expression (required) – This parameter represents the expression that you want to convert to an Integer wherein...

1 minute read.

Finding Last Row or Column in Excel VBA

Finding Last Row or Column in VBA Finding the last used row, column, or cell is one very commonly used task when we write macros and VBA applications.  Like other codes...

5 minutes 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 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 LTrim Function

VBA LTrim Function: The LTrim function in VBA removes the leading spaces from a supplied text string. Syntax LTrim (String) Parameter String (required) - This parameter represents he text string that you want to remove...

1 minute read.

Excel VBA ABS Function

VBA ABS Function: The ABS function in VBA returns the absolute value of the specified number. Syntax Abs (Number) Parameter Number (required) – This parameter represents the number that you want the absolute value of. Return This...

1 minute read.

Excel VBA Sgn Function

VBA Sgn Function: The Sgn function in VBA returns an integer (+1, 0, or -1), stating the arithmetic sign for the specified number. Syntax Sgn (Number) Parameter Number (required) –This parameter represents the number that...

1 minute read.

Excel VBA Left Function

VBA Left Function: The Left function in VBA returns a substring from the start of the specified string. Syntax Left (Str, Length) Parameter Str (required) – This parameter represents the string that you want to extract...

1 minute read.

VBA runtime error 1004

What is 1004 error?  VBA 1004 Error, also known as object-defined or application-defined, is a runtime error in VBA, usually, if the specified range does not exist in the worksheet or if the Application...

6 minutes read.