How to Use the Range Property in Excel VBA (the Ultimate Guide)

 

 

1. Using Range Address

To represent a single cell or a range of cells, you can use the Range Object, where the argument names the range. Here is the syntax to specify a range:

To specify a range that has one cell, cell B6, enter:

Range ("B6")

Referring to a range of cells, for example, range B6 to E16, there are two acceptable ways:

Range("B6:E16")

and

Range("B6", "E16")
Note:

The above syntaxes use double quotations (” “) to enclose the range address. Alternatively, you can type quickly using the square brackets without quotation marks. For example:

You may use [B6:E16] instead of Range(“B6:E16”) to refer to the range B6:E16.


2. Using Cells Property

You can use the Cells property to refer to a range in VBA. Using the Cells property is useful while looping through rows or columns. The Cells property takes two arguments:

Cells (Row, Column)

For the Row arguments, you only need to use numeric values. You may use either a string or numeric value for Column arguments. In the below example, both code lines refer to A1:E5:

Range(Cells(1,1),Cells(5,5))

or

Range (Cells(1,”A”),Cells(5,”E”))
Note:

To refer to a single cell, you can simply use the lines below without mentioning the Range object.

Cells(6, 2) or Cells(6, “B”)


3. Referring to Entire Rows as Range

Use the Range object in VBA to refer to an entire row or multiple rows.

Here are the syntaxes for both single and multiple rows.

  • For single row range:
Range("6:6")
  • For multi-row range:
Range("6:8")

4. Setting Entire Columns as Range

To set an entire column or multiple columns, use the following syntaxes.

  • For single-column range:
Range ("B:B")
  • For multiple column range:
Range ("B:E")

5. Setting Non-Contagious Cells as Range

To set non-contagious cells as a range in VBA, use Comma (,) to separate each area. For referring to range B6:C6 and E6:E16 at once, you can use this line:

Range("B6:C16, E6:E16")

6. Using the Resize Property to Set Range

The Resize property in Excel VBA changes the size of a range.

Your current range is B6, and you want to resize it to B6:E9. Therefore, the syntax of the Range object in VBA is-

Range("B6").Resize(4, 4)

Read More: VBA to Set Range in Excel


How to Set a Dynamic Range in Excel VBA

In the previous examples, you specified a fixed range size when using the VBA Range object. However, you often don’t know the exact range size when dealing with variable ranges. In such situations, you need dynamic ranges in Excel VBA. Here are a few ways to set a dynamic range in VBA.


1. Setting Range Variable to Selection

You can set range variables to selection in Excel VBA and then use the variables to access properties and methods. Consider the below dataset where the range B6:E9 is selected:

Setting variable to selected B6:E9

Using the following code to change the cell color of the selected region as range variables:

Sub SettingRangeVariabletoSelection()
'Developed by ExcelDemy
Dim rng As Range
Set rng = Selection
rng.Interior.Color = RGB(245, 220, 202)
End Sub

Thus, the interior color of the selected range changes.

Changing fill color to Selected variables


2. Using Input Box to Select Range

In this method, you will use an input box to select a range and change its color. Consider the previous dataset and run the below VBA code:

Sub UsingInputBoxtoSelectRange()
'Developed by ExcelDemy
    Set rng = Application.InputBox("Select a range:", Type:=8)
    rng.Interior.Color = RGB(245, 220, 220)
End Sub
  • Enter the desired range in the message box and select OK. Here, we input range B6:E9.

Selecting B6:E9 in VBA input box

As a result, the interior color of the desired range changes.

Selected range fill color changes using input box


3. Applying UsedRange Property

Consider a dataset where you constantly enter values and do not know how big it could get, you can use the UsedRange property. The following VBA code will select the used region:

Sub ApplyingUsedRangeProperties()
'Developed by ExcelDemy
ActiveSheet.UsedRange.Select
End Sub

Running the VBA code selects the whole used region.

Applying Usedrange Property in Excel


4. Using CurrentRegion Property

This CurrentRegion property can cover all the contagious cells of the active cell region. Here is the VBA code to select the contagious cells of B6:

Sub UsingCurrentRegionProperties()
'Developed by ExcelDemy
Range("B6").CurrentRegion.Select
End Sub

The current region of cell B6 gets selected.

CurrentRange is selected with CurrentRegion property


5. Setting Range with Variable Row and Column

You want to set a range with variable row and column numbers. To do this, specify the first row and column with variables and use the End property to get the last row and column. The End property for the Range object refers to the last cell within the range. Consider the following VBA code:

Sub SettingVariableRowColumn()
'Developed by ExcelDemy
    first_row = 5
    first_col = 2 ' or "B"
    last_row = Cells(Rows.Count, first_col).End(xlUp).Row
    last_col = Cells(first_row, Columns.Count).End(xlToLeft).Column
    Range(Cells(first_row, first_col), Cells(last_row, last_col)).Select
End Sub

Here, we have assigned the first row and first column as 5 and 2, which indicates cell B5. Then, we can assign the last rows and columns using the End property. After that, we selected the region by setting the range with variable row and column numbers.

Setting range with variable row and columns in VBA

Read More: VBA to Use Range Based on Column Number in Excel


How to Set a Range Using Named Range in Excel VBA

You can set a range using Named Range in Excel VBA by enclosing the range name with double-quotations in the Range object argument. Let’s assume you have a Named Range named myRng that represents range B6:E16.

Name Manager displays B6:E16 as myRng

In the following VBA code, set the range using the named range:

Sub SettingRangeUsingNamedRange()
'Developed by ExcelDemy
    Range("myRng").Select
End Sub

As a result, the Named Range gets selected.

Setting range using Named Range with VBA


How to Select Range with VBA in Excel

You can select a range using the Select method of the Range object in VBA. In the previous sections, you have learned how to specify a range. Here, you will see some practical examples of selecting ranges with VBA.


1. Selecting a Single Cell

Let’s consider the dataset that represents the sales data of some brands.

Selecting a cell with VBA range object dataset

To select a single cell B6, run the below VBA code:

Sub SelectingaSingleCell()
'Developed by ExcelDemy
    Range("B6").Select
End Sub

Running the code selects the cell B6.

Selecting a cell with VBA range object output


2. Selecting Entire Rows

To select the entire rows 6 to 8, use the following VBA code:

Sub SelectingEntireRows()
'Developed by ExcelDemy
Range("6:8").Select
End Sub

Selecting entire rows with VBA Range Object


3. Selecting Entire Columns

Select the entire columns D & E using the following VBA code:

Sub SelectingEntireColumn()
'Developed by ExcelDemy
    Range("D:E").Select
End Sub

Select entire columns


4. Selecting a Contagious Range

You can also select all the contagious cells at once. Consider the below VBA code:

Sub SelectingContagiousRange()
'Developed by ExcelDemy
    Range("B6", "E16").Select
End Sub

The code selects every contagious cell of B6:E16.

Selecting contagiousRange


5. Selecting a Non-Contagious Range

Select the non-contagious cells of the same dataset. Use the below VBA code:

Sub SelectingNonContagiousCells()
'Developed by ExcelDemy
Range("B6:C16, E6:E16").Select
End Sub

After running the code, two mentioned areas in the code were selected.

Selecting non-contagious data


6. Selecting a Used Range

Select the used range of your active sheet using the Used Range property in VBA. Use the following VBA code:

Sub SettingUsedRangeinColumn()
'Developed by ExcelDemy
ActiveSheet.UsedRange.Select
End Sub

Select the entire range of used items on the active sheet.

Selecting usedrange in column using UsedRange property


7. Selecting the Last Cell in a Range

If you want to select the last cell of a large column without scrolling, you can use the below VBA code:

Sub SelectingLastCellInRange()
Range("B6").End(xlDown).Select
End Sub

The last cell of the column B is selected.

Selecting last cell in dataset using End Property


8. Selecting a Range from the Active Cell to the End

Let’s say you have a selected cell in the dataset.

Selected cell D7 to dataset

You can select range from the active cell in Excel with VBA Range Object to the end. Here is the VBA code:

Sub SelectfromActiveCelltoEnd()
'Developed by ExcelDemy
Range(ActiveCell.End(xlDown), ActiveCell.End(xlToRight)).Select
End Sub

The code selects the range up to the last cells.

Selecting range from active cell to end using VBA range property

Read More: How to Select Range Based on Cell Value VBA


9. Stopping on Multi-Select Using VBA in Excel

Using Range Object in VBA, you can stop an operation when you have multiple selections in your data. For Example, in the dataset, we have multiple selections of different areas.

Multiple selected cells in dataset

The following VBA code stops any operations on multiple selections:

Sub StoppingOnMultiSelection()
'Developed by ExcelDemy
    selected_area_count = Selection.Areas.Count
    If selected_area_count > 1 Then
    MsgBox "Cannot carry out the task on multiple selections"
    End If
End Sub

As a result, the code stops any activity on multiple selections.

Message box to stop on multi-selections


How to Apply Offset Property of Range in Excel VBA

You can apply the active cell Offset Property in the VBA Range object to offset a range selection. The Offset property shifts the position of the range, and the Resize property enlarges the size of the range to the specified range. Let’s say you have an active cell B5 in your dataset.

Selected cell B5 in dataset

The following VBA code offsets your selection to one row and one column and resizes the selection to cover 11 rows and 1 column:

Sub ApplyOffsetProperties()
'Developed by ExcelDemy
    ActiveCell.Offset(1, 1).Resize(11, 1).Select
End Sub

Running the code results in the range B8:B16 being selected.

Range offset & resize property applied to offset selection

Read More: How to Use VBA Range Offset


How to Loop Through a Range in Excel VBA

1. Looping Through Each Cell in a Range

This procedure shows how VBA For Each loops through each cell in range C6:D15. In this example, you will loop through the product’s unit price and quantity of the specified range and calculate the tax in the corresponding E column.

Looping through each cell in a range dataset

The VBA code calculates the tax values within the loop and enters them in E6:E15. Here is the VBA code:

Sub LoopingForEachCell()
'Developed by ExcelDemy
Set target_range = Range("E6:E15")
tax_value = 0.05
For Each cell In target_range
    cell.Value = cell.Offset(0, -2).Value * cell.Offset(0, -1).Value * tax_value
Next cell
End Sub

As a result, the tax values appear in E6:E15.

Tax calculated looping through each cell in a range using VBA

Read More: VBA for Each Cell in Range in Excel


2. Looping Through Each Row in a Range

Now, we want VBA For Each loop to loop through each row 6 to 15. In the loop, we will look for odd or even rows and highlight the odd rows. Use the below VBA code:

Sub LoopingForEachRow()
'Developed by ExcelDemy
    Set working_range = Range("B6:E15")
    For i = 1 To working_range.Rows.Count
        If i Mod 2 = 0 Then
            working_range.Rows(i).Interior.Color = RGB(245, 220, 220)
        Else
            working_range.Rows(i).Interior.Color = xlNone
        End If
    Next i
End Sub

The code highlights the odd rows, and the even rows remain the same.

Odd rows fill color change looping through each loop using VBA

Read More: Loop through a Range for Each Cell with Excel VBA


How to Work with VBA Range Properties in Excel

In this section, you will look closely at some useful Range properties in VBA. The Range Property represents cells, rows, and columns and manipulates cell formattings. Here are a few examples of Range Property in Excel VBA.


1. Changing Fill Color

Consider the below dataset where we want to change the fill color of the range B6:E16.

Changing fill color using VBA range object dataset

Sub ChangingFillColor()
'Developed by ExcelDemy
    Range("B6:E16").Interior.Color = RGB(245, 220, 220)
End Sub

The fill color of the mentioned range changes.

Changing fill color using VBA range object output


2. Changing Font Style, Size and Color

Similarly, you can change the font style, size, and color using the Range Property. Let’s change the formatting of range E6:E16. Use the following VBA code:

Sub ChangeFontStyle()
'Developed by ExcelDemy
    Dim myRange As Range
    Set myRange = Range("E6:E16")
    With myRange.Font
        .Size = 11
        .Bold = True
        .Italic = True
        .Color = RGB(220, 120, 140)
    End With
End Sub

The new formatting appears in the desired range.

Changing font style, size and color using VBA range object


3. Applying Border

If your sheet has borderless data, as shown below, you can apply borders using VBA with Range Property.

Applying border using VBA range object dataset

Use the following VBA code to apply borders:

Sub ApplyingBorders()
'Developed by ExcelDemy
    Dim myRange As Range
    Set myRange = Range("B5").CurrentRegion
    With myRange.Borders
        .LineStyle = xlContinuous
        .Color = RGB(208, 206, 206)
        .TintAndShade = 0
        .Weight = xlThin
    End With
End Sub

Thus, you obtain the borders in the range.

Applying border using VBA range object output


4. Changing Alignment

You can customize the cell alignment using this property. To change the alignment of the range, use the following VBA code:

Sub ChangingAlignment()
'Developed by ExcelDemy
    Dim myRange As Range
    Set myRange = Range("B6:E16")
    With myRange
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlVAlignCenter
    End With
End Sub

The cell alignments of the range B6:E16 move vertically and horizontally to the center.

Changing alignment using VBA range object output


How to Work with VBA Range Methods in Excel

In VBA, methods are built-in functions that belong to specific objects and perform actions on them. The Range object in VBA provides various methods, each with its own specific purpose. Here are some of the most commonly used methods: Value, Clear, Copy, Delete, etc.


Copy-Pasting Range

Copy and paste a range with VBA using the Copy and Paste method with the Range object. See the below dataset where you will copy range B6:E16 of the Copy Paste Range worksheet.

Copy & pasting using VBA range object dataset

Run the below VBA code:

Sub CopyPasteRange()
'Developed by ExcelDemy
    Sheets("Copy Paste Range").Activate
    Range("B5:E16").Select
    Selection.Copy
    Sheets("Target Range").Activate
    Range("B2").Select
    ActiveSheet.Paste
End Sub

After running the code, we get the copied value in the Target Range sheet.

Copied range pasted in Target Range sheet using VBA range object


Counting Total Cells in a Range

If you have a selected range as given below, you can count the total cells using the Count method of the VBA Range object.

Selecting range B6:E16 to count total cells with VBA

Consider the below VBA code where we have used the Count method:

Sub CountTotalCellsInRange()
'Developed by ExcelDemy
    Set target_range = Selection
    MsgBox "Total Cells Count: " & target_range.Cells.Count
End Sub

The code will show you the total number of cells in a message box.

Total number of cells in a range found using VBA range object


Clearing Contents of a Range

The Range object uses the ClearContents method to clear the contents in VBA from the specified range E6:E16 of the data below.

Clearing range using VBA range object

Use the following VBA code and run it.

Sub ClearContentsofRange()
'Developed by ExcelDemy
    Range("E6:E16").ClearContents
End Sub

As a result, the data of the specified range is cleared.

Contents cleared using VBA range object


Autofill a Range

Let’s say you have calculated a tax value in E6 based on the unit price and quantity using the given formula in F6. Using the AutoFill method, you can autofill the range in VBA.

Tax value obtained in E6

Here is the VBA code to autofill the range E6:E15:

Sub AutoFillRange()
'Developed by ExcelDemy
    Range("E6").AutoFill Range("E6:E15")
End Sub

Thus, you obtain the rest of the tax values.

Auto Filtering E6:E16 using VBA range object


Merging Cells in a Range

Imagine the scenario below, where the Brand column has similar values consecutively, and you can merge the cells with similar values for better visibility.

Merging cells in a range using VBA dataset

Use the Merge method in the VBA code provided below and execute it.

Sub MergeCells()
'Developed by ExcelDemy
Application.DisplayAlerts = False
    Range("B6:B9").Merge
    Range("B10:B13").Merge
    Range("B14:B16").Merge
Application.DisplayAlerts = True
End Sub

We obtain cells with similar data merged.

Merged cells in column B using VBA range object


Filtering a Range Using Auto Filter

The AutoFilter method in the Range object can filter data based on criteria. In the below dataset, we will filter the range B5:E16 when the values of range E6:E16 are less than 800.

Filtering range dataset

The following VBA code uses the .AutoFilter method to filter.

Sub FilteringRange()
'Developed by ExcelDemy
 Range("B5:E16").AutoFilter Field:=4, Criteria1:="<800"
End Sub

Running the code gets us the filtered range based on the specified conditions.

Filtered range found using VBA range object


Using Advanced Filter Method

You can also use auto and Advanced filters in VBA to filter range B5:E16 based on the criteria in range G5:H6. The Advanced Filter method copies the filtered range and pastes it to a specified location.

Using Advanced Filter based on criteria in G5:H6 dataset

  • Use the VBA code with the .AdvancedFilter method and run it.
Sub UsingAdvancedFiltertoRange()
' Developed by ExcelDemy
        Range("B5:E16").AdvancedFilter _
        Action:=xlFilterCopy, _
        CriteriaRange:=Range("G5:H6"), _
        CopyToRange:=Range("G8")
End Sub

The filtered range appears after running the code.

Advanced filter range found using VBA range object


Sorting a Range

In the given dataset, we will sort range using VBA based on the range E6:E16 in ascending order.

Sorting a range dataset

Use the given VBA code and run it.

Sub SortRange()
'Developed by ExcelDemy
    Dim rngToSort As Range
    Set rngToSort = Range("B5:E16")
    rngToSort.Sort key1:=rngToSort.Columns(4), _
                    order1:=xlAscending, _
                    Header:=xlYes
End Sub

Thus, we get the sorted range based on the prices.

Sorted data found


Finding Unique Values in a Range

Let’s highlight the unique values from range E6:E16 using the Range object in the given example.

Finding unique values in a dataset

Here is the VBA code to highlight the unique value of the range:

Sub FindUniqueValues()
'Developed by ExcelDemy
    Dim rng As Range
    Dim cell As Range
    Set rng = Range("E6:E16")
    rng.Interior.ColorIndex = xlNone
    For Each cell In rng
        If Application.WorksheetFunction.CountIf(rng, cell.Value) = 1 Then
            cell.Interior.Color = RGB(245, 220, 220)
        End If
    Next cell
End Sub

After running the code, it will highlight the unique value.

Unique values highlighted using VBA range object


Removing Duplicates from a Range

Now, you will use the RemoveDuplicates method to remove duplicates in Excel VBA. See the range E6:E16 below, which has duplicate values 620.

Removing Duplicates from a range dataset

Use the VBA code and run.

Sub RemoveDuplicates()
'Developed by ExcelDemy
ActiveSheet.Range("B6:E16").RemoveDuplicates Columns:=Array(1, 2, 3, 4), Header:=xlNo
End Sub

As you can see, there was one duplicate value and its entire row disappeared.

Duplicates removed using VBA range object


Finding Any Value in a Range

Now, you will search for “Notebook” in range B6:E16 using the Find Method in Excel VBA Range Object. The Find method searches any specified value and returns a message box showing its location if found. The method will return the first location only if there are multiple locations. Use the following VBA to search:

Sub FindAnyValue()
'Developed by ExcelDemy
    Dim searchValue As Variant
    Dim searchRange As Range
    Dim foundCell As Range
    searchValue = "Notebook"
    Set searchRange = Range("B6:E16")
    Set foundCell = searchRange.Find(What:=searchValue, LookIn:=xlValues, LookAt:=xlWhole)
    If Not foundCell Is Nothing Then
        MsgBox "The Value is at cell " & foundCell.Address
    Else
        MsgBox "Value not found in the specified range."
    End If
End Sub

The code finds the value in C6.

Using Find property to find any value


Converting Text to Columns

You might need to convert text to columns in VBA for data visualization. See the dataset below, which lists full names in the range B6:B16. We will divide the full names into first and last names in separate columns using the TextToColumns method.

Converting text to columns dataset

  • The VBA code divides the names and places them in columns C & D:
Sub ConvertTextToColumns()
'Developed by ExcelDemy
    Application.DisplayAlerts = False
    Dim rng As Range
    Set rng = Range("B6:B16")
    rng.TextToColumns Destination:=Range("C6"), _
        DataType:=xlDelimited, _
        TextQualifier:=xlTextQualifierNone, _
        Tab:=False, _
        Semicolon:=False, _
        Comma:=False, _
        Space:=True, _
        Other:=False, _
        FieldInfo:=Array(Array(1, 1), Array(2, 1)), _
        DecimalSeparator:=".", _
        ThousandsSeparator:=",", _
        TrailingMinusNumbers:=True
    Application.DisplayAlerts = True
End Sub

The code converts the text into columns and returns the first and last names.

Text converts to columns using range object


Calculating Range

Lastly, you can calculate a range in VBA using the Calculate method. The Calculate method allows you to compute values across all open workbooks, specific workbooks, targeted worksheets, ranges, columns, or rows. If you have a formula range, the Calculate method can recalculate or refresh that range. The following VBA recalculates the range.

Sub CalculateRange()
'Developed by ExcelDemy
Range("E6:E15").Calculate
MsgBox "The range has been recalculated!", vbInformation
End Sub

After running the code, the specified range will be recalculated.

Recalculating range using Calculate method


How to Convert Array to Range or Range to Array Using VBA in Excel

In this section, you will convert an array to a range and range to an array using the Range object in Excel VBA.

1. Convert Array to Range

If you have an array, insert it in the VBA code and place it in range E6:E16 of the given dataset.

Converting array to range dataset

The VBA code uses the Range object to specify the range and uses the range to hold the array.

Sub ConvertArrayToRange()
'Developed by ExcelDemy
    Dim myArray As Variant
    Dim myRange As Range
    myArray = Array(400, 500, 550, 600, 650, 500, 700, 730, 780, 980, 1000)
   Set myRange = Range("E6").Resize(UBound(myArray) + 1, 1)
    myRange.Value = Application.Transpose(myArray)
End Sub

Hence, you find the array stored in the specified range.

Array converted to range using range object


2. Convert Range to Array

Alternatively, you can use the same range and convert them into arrays using the Range object. The below VBA code will do the task using a message box.

Sub ConvertRangeToArray()
'Developed by ExcelDemy
    Dim myRange As Range
    Dim dataArray As Variant
    Dim i As Long, j As Long
    Dim resultString As String
    Set myRange = Range("E6:E16")
    dataArray = myRange.Value
    For i = LBound(dataArray, 1) To UBound(dataArray, 1)
        For j = LBound(dataArray, 2) To UBound(dataArray, 2)
            resultString = resultString & "Value at (" & i & ", " & j & "): " & dataArray(i, j) & vbCrLf
        Next j
    Next i
    MsgBox resultString, vbInformation, "Array Values"
End Sub

The above procedure returns a message box showing the array in the message box.

Range converted to array using range object


How to Reference Range from Another Sheet with Excel VBA

To reference a range from another sheet, use the Range object to specify the range in VBA. Here is the VBA code for referring to a range E6:E16 from the Calculate Range sheet.

Sub ReferRangefromAnotherSheet()
'Developed by ExcelDemy
    Dim myRange As Range
    Set myRange = Worksheets("Calculate Range").Range("E6:E16")
    Dim rangeValues As Variant
    rangeValues = myRange.Value
    Dim resultString As String
    Dim i As Long, j As Long
    For i = LBound(rangeValues, 1) To UBound(rangeValues, 1)
        For j = LBound(rangeValues, 2) To UBound(rangeValues, 2)
            resultString = resultString & rangeValues(i, j) & vbTab
        Next j
        resultString = resultString & vbCrLf
    Next i
    MsgBox resultString, vbInformation, "Range Items"
End Sub

After running the code, you will get a message box displaying the specified range from the worksheet.

Referencing range from another sheet using VBA range object

Read More: How to Use Excel VBA to Copy Range to Another Excel Sheet


How to Reference Range from Another Workbook with Excel VBA

The below procedure will specify a range from another workbook using the Range object in Excel VBA.

  • Specify your file location in the VBA code and run it.
Sub ReferRangeFromAnotherWorkbook()
'Developed by ExcelDemy
    Dim otherWorkbook As Workbook
    Dim myRange As Range
    Dim otherWorkbookPath As String
    otherWorkbookPath = "C:\Users\YOUSUF\Desktop\Target File.xlsm"
    Set otherWorkbook = Workbooks.Open(otherWorkbookPath)
    Set myRange = otherWorkbook.Worksheets("Calculate Range").Range("E6:E16")
    Dim rangeValues As Variant
    rangeValues = myRange.Value
    Dim resultString As String
    Dim i As Long, j As Long
    For i = LBound(rangeValues, 1) To UBound(rangeValues, 1)
        For j = LBound(rangeValues, 2) To UBound(rangeValues, 2)
            resultString = resultString & rangeValues(i, j) & vbTab
        Next j
        resultString = resultString & vbCrLf
    Next i
    otherWorkbook.Close SaveChanges:=False
    MsgBox resultString, vbInformation, "Range Items"
End Sub

In this way, you can access a range of other workbooks.

Referencing range from another workbook


What to Do When Macro Returns Subscript Out of Range Error in Excel VBA?

The Subscript Out of Range error can occur for mainly these reasons:

  • Trying to access a cell beyond the range’s actual size.
  • Using properties or methods of a non-existent Range object.
  • Accidentally deleting definitions in a Named Range.
  • The defined worksheet in VBA isn’t open or accessible on the user’s computer.
  • The worksheet or the range is nonexistent.
  • The provided worksheet name doesn’t match the actual name of the desired sheet, etc.

In the scenario below, the Range object could not find any Fixed range. As a result, it shows the Run-time error ‘9’: Subscript out of range error.

Subscript out of range error

To fix the situation, the proper way is to put the correct sheet name in the code. You can add an error handler like the VBA code below to avoid this error.

Sub FixSubscriptOutOfRangeError()
'Developed by ExcelDemy
    On Error Resume Next
     Worksheets("Fixed").Activate
    If Err.Number <> 0 Then
        MsgBox "Worksheet 'Fixed' not found.", vbExclamation
        Err.Clear
        Exit Sub
    End If
    On Error Resume Next
    Range("E6:E16").Select
    If Err.Number <> 0 Then
        MsgBox "Range [E6:E16] not found on the 'Fixed' worksheet.", vbExclamation
        Err.Clear
        Exit Sub
    End If
    On Error GoTo 0
End Sub

Running the code returns an error message box saying the worksheet is not found.

Fixing Subscript out of range error


Download the Practice Workbook


Related Readings

Get FREE Advanced Excel Exercises with Solutions!

Tags:

Rifat Hassan
Rifat Hassan

Rifat Hassan, BSc, Electrical and Electronic Engineering, Bangladesh University of Engineering and Technology, has worked with the ExcelDemy project for almost 2 years. Within these 2 years, he has written over 250 articles. He has also conducted a few Boot Camp sessions on effective coding, especially Visual Basic for Applications (VBA). Currently, he is working as a Software Developer to develop and deploy additional add-ins to enhance the customers with a more sophisticated experience with Microsoft Office Suits,... Read Full Bio

We will be happy to hear your thoughts

Leave a reply

Advanced Excel Exercises with Solutions PDF

 

 

ExcelDemy
Logo