Range offset in excel vba

Свойство Offset объекта Range, возвращающее смещенный диапазон, в том числе отдельную ячейку, в коде VBA Excel. Синтаксис, параметры, примеры.

Offset – это свойство объекта Range, возвращающее диапазон той же размерности, но смещенный относительно указанного диапазона на заданное количество строк и столбцов.

Синтаксис

Синтаксис свойства Range.Offset:

Expression.Offset (RowOffset, ColumnOffset)

Expression – это выражение (переменная), возвращающее исходный объект Range, относительно которого производится смещение.

Параметры

RowOffset – это параметр, задающий смещение диапазона по вертикали относительно исходного на указанное количество строк.

Значение RowOffset Направление смещения
Отрицательное вверх
Положительное вниз
0 (по умолчанию) нет смещения

ColumnOffset – это параметр, задающий смещение диапазона по горизонтали относительно исходного на указанное число столбцов.

Значение ColumnOffset Направление смещения
Отрицательное влево
Положительное вправо
0 (по умолчанию) нет смещения

Необходимо следить за тем, чтобы возвращаемый диапазон не вышел за пределы рабочего листа Excel. В противном случае VBA сгенерирует ошибку (Пример 3).

Примеры

Пример 1
Обращение к ячейкам, смещенным относительно ячейки A1:

Sub Primer1()

  Cells(1, 1).Offset(5).Select

    MsgBox ActiveCell.Address

  Cells(1, 1).Offset(, 2).Select

    MsgBox ActiveCell.Address

  Cells(1, 1).Offset(5, 2).Select

    MsgBox ActiveCell.Address

End Sub

Пример 2
Обращение к диапазону, смещенному относительно исходного:

Sub Primer2()

  Range(«C8:F12»).Offset(3, 5).Select

    MsgBox Selection.Address

End Sub

Пример 3
Пример ошибки при выходе за границы диапазона рабочего листа:

Sub Primer3()

On Error GoTo ErrorText

  Cells(1, 1).Offset(3).Select

Exit Sub

ErrorText:

  MsgBox «Ошибка: « & Err.Description

End Sub

Using OFFSET with the range object, you can navigate from one cell to another in the worksheet and you can also select a cell or a range. It also gives you access to the properties and methods that you have with the range object to use, but you need to specify the arguments in the OFFSET to use it.

Use OFFSET with the Range Object

  1. Specify the range from where you want to start.
  2. Enter a dot (.) to get a list of properties and methods.
  3. Select the offset property and specify the arguments (row and column).
  4. In the end, select property to use with the offset.

Select a Range using OFFSET

You can also select a range which is the number of rows and columns aways from a range. Take the below line of code, that selects a range of two cells which is five rows down and 3 columns right.

Range("A1:A2").Offset(3, 2).Select

Apart from that, you can also write code to select the range using a custom size. Take an example of the following code.

Range(Range("A1").Offset(1, 1), Range("A1").Offset(5, 2)).Select

To understand this code, you need to split it into three parts.

First thing first, in that range object, you have the option to specify the first cell and the last of the range.

Now let’s come back to the example:

  • In the FIRST part, you have used the range object to refer to the cell that is one row down and one column right from the cell A1.
  • In the SECOND part, you have used the range object to refer to the cell that us five rows down and two columns right from the cell A1.
  • In the THRID part, you have used the cells from the part first and second to refer to a range and select it.

Using OFFSET with ActiveCell

You can also use the active cell instead of using a pre-defined range. That means you’ll get a dynamic offset to select a cell navigating from the active cell.

ActiveCell.Offset(5, 2).Select

The above line of code will select the cell which is five rows down and two columns right from the active cell.

Using OFFSET with ActiveCell to Select a Range

Use the following code to select a range from the active cell.

Range(ActiveCell.Offset(1, 1), ActiveCell.Offset(5, 2)).Select

To understand how this code works, make sure to see this explanation.

Copy a Range using OFFSET

Range(Range("A1").Offset(1, 1), Range("A1").Offset(5, 2)).Copy
Range(ActiveCell.Offset(1, 1), ActiveCell.Offset(5, 2)).Copy

Using Cells Property with OFFSET

You can also use the OFFSET property with the CELLS property. Consider the following code.

Cells(1, 3).Offset(2, 3).Select

The above code first refers to the cell A1 (as you have specified) with row one and column one using the cells property, and then uses the offset property to selects the cell which is two rows down and three columns.

More Tutorials

    • Count Rows using VBA in Excel
    • Excel VBA Font (Color, Size, Type, and Bold)
    • Excel VBA Hide and Unhide a Column or a Row
    • Excel VBA Range – Working with Range and Cells in VBA
    • Apply Borders on a Cell using VBA in Excel
    • Find Last Row, Column, and Cell using VBA in Excel
    • Insert a Row using VBA in Excel
    • Merge Cells in Excel using a VBA Code
    • Select a Range/Cell using VBA in Excel
    • SELECT ALL the Cells in a Worksheet using a VBA Code
    • ActiveCell in VBA in Excel
    • Special Cells Method in VBA in Excel
    • UsedRange Property in VBA in Excel
    • VBA AutoFit (Rows, Column, or the Entire Worksheet)
    • VBA ClearContents (from a Cell, Range, or Entire Worksheet)
    • VBA Copy Range to Another Sheet + Workbook
    • VBA Enter Value in a Cell (Set, Get and Change)
    • VBA Insert Column (Single and Multiple)
    • VBA Named Range | (Static + from Selection + Dynamic)
    • VBA Sort Range | (Descending, Multiple Columns, Sort Orientation
    • VBA Wrap Text (Cell, Range, and Entire Worksheet)
    • VBA Check IF a Cell is Empty + Multiple Cells

    ⇠ Back to What is VBA in Excel

    Helpful Links – Developer Tab – Visual Basic Editor – Run a Macro – Personal Macro Workbook – Excel Macro Recorder – VBA Interview Questions – VBA Codes

    Return to VBA Code Examples

    The Offset Property is used to return a cell or a range, that is relative to a specified input cell or range.

    Using Offset with the Range Object

    You could use the following code with the Range object and the Offset property to select cell B2, if cell A1 is the input range:

    Range("A1").Offset(1, 1).Select

    The result is:

    Using the Offset Property With the Range Object

    Notice the syntax:

    Range.Offset(RowOffset, ColumnOffset)

    Positive integers tells Offset to move down and to the right. Negative integers move up and to the left.

    The Offset property always starts counting from the top left cell of the input cell or range.

    Using Offset with the Cells Object

    You could use the following code with the Cells object and the Offset property to select cell C3 if cell D4 is the input range:

    Cells(4, 4).Offset(-1, -1).Select

    Selecting a Group of Cells

    You can also select a group of cells using the Offset property. The following code will select the range which is 7 rows below and 3 columns to the right of input Range(“A1:A5”):

    Range("A1:A5").Offset(7, 3).Select

    Range(“D8:D12”) is selected:

    Using the Offset Property to Select a Group of Cells in VBA

    VBA Coding Made Easy

    Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
    vba save as

    Learn More!

    How to use VBA Range.Offset Method?

    May 02, 2017 in Excel

    Range.Offset is a property of the VBA range object that is used when you want to point the cell selection to a specific column and row address. For an instance, if you want to skip some information like row header or document title.

    Syntax

    expression .Offset(RowOffset, ColumnOffset)

    expression A variable that represents a Range object.

     Parameters

    Name Required/Optional Data Type Description
    RowOffset Optional Variant
    The number of rows (positive, negative, or 0 (zero)) by which the range is to be offset. Positive values are offset downward, and negative values are offset upward. The default value is 0.
    ColumnOffset Optional Variant The number of columns (positive, negative, or 0 (zero)) by which the range is to be offset. Positive values are offset to the right, and negative values are offset to the left. The default value is 0.

    Below are the sample codes:

    1. To activate the cell five columns to the right and five rows down of the selected cell in the worksheet.
     Worksheets("Sample").Activate
    ActiveCell.Offset(rowOffset:=5, columnOffset:=5).Activate 

    1. This example will select the table without selecting the header row. Selected cell should be somewhere in the table.
    Set tbl = ActiveCell.CurrentRegion tbl.Offset(1, 0).Resize(tbl.Rows.Count - 1, _  tbl.Columns.Count).Select 

    3. The following sample will select the range 4 rows below and 3 columns to the right of Range(“B1:B2”). Offset property always takes the top left cell of a range as the starting point.

     Dim OffsetSample As Range
     Set OffsetSample = Range("B1:B2")
     OffsetSample.Offset(4, 3).Select 

    Excel VBA OFFSET Function

    VBA Offset function one may use to move or refer to a reference skipping a particular number of rows and columns. The arguments for this function in VBA are the same as those in the worksheet.

    For example, assume you have a data set like the one below.

    OFFSET Data

    Now from cell A1, you want to move down four cells and select that 5th cell, the A5 cell.

    Similarly, if you want to move two rows down from the A1 cell and two columns to the right, select that cell, i.e., the C2 cell.

    In these cases, the OFFSET function is very helpful. Especially in VBA OFFSET, the function is just phenomenal.

    Table of contents
    • Excel VBA OFFSET Function
      • OFFSET is Used with Range Object in Excel VBA
      • Syntax of OFFSET in VBA Excel
      • Examples
        • Example #1
        • Example #2
        • Example #3
        • Example #4
      • Things to Remember
      • Recommended Articles

    OFFSET is Used with Range Object in Excel VBA

    In VBA, we cannot directly enter the word OFFSET. Instead, we need to use the VBA RANGE objectRange is a property in VBA that helps specify a particular cell, a range of cells, a row, a column, or a three-dimensional range. In the context of the Excel worksheet, the VBA range object includes a single cell or multiple cells spread across various rows and columns.read more first. Then, from that range object, we can use the OFFSET property.

    In Excel, the range is nothing but a cell or range of the cell. Since OFFSET refers to cells, we need to use the object RANGE first, and then we can use the OFFSET method.

    Syntax of OFFSET in VBA Excel

    OFFSET Formula

    • Row Offset: How many rows do you want to offset from the selected cell? Here the selected cell is A1, i.e., Range (“A1”).
    • Column Offset: How many columns do you want to offset from the selected cell? Here, the selected cell is A,1, i.e., Range (“A1”).

    Examples

    You can download this VBA OFFSET Template here – VBA OFFSET Template

    Example #1

    Consider the below data for demonstration.

    OFFSET Example 1

    Now, we want to select cell A6 from cell A1. But, first, start the macro and reference cell using the Range object.

    Code:

    Sub Offset_Example1()
    
        Range("A1").offset(
    
    End Sub

    VBA OFFSET Example 1-1

    Now, we want to select cell A6. Then, we want to go down 5 cells. So, enter 5 as the parameter for Row Offset.

    Code:

    Sub Offset_Example1()
    
        Range("A1").offset(5
    
    End Sub

    VBA OFFSET Example 1-2

    Since we are selecting the same column, we leave out the column part. Close the bracket, put a dot (.), and type the method “Select.”

    Code:

    Sub Offset_Example1()
    
        Range("A1").Offset(5).Select
    
    End Sub

    VBA OFFSET Example 1-3

    Now, run this code using the F5 key, or you can run it manually to select cell A6, as shown below.

    VBA OFFSET Example 1-4

    Output:

    VBA OFFSET Example 1-5

    Example #2

    Now, take the same data, but here will also see how to use the column offset argument. Now, we want to select cell C5.

    Since we want to select cell C5 firstly, we want to move down four cells and take the right two columns to reach cell C5. The below code would do the job for us.

    Code:

    Sub Offset_Example2()
    
        Range("A1").Offset(4, 2).Select
    
    End Sub

    VBA OFFSET Example 2

    We run this code manually or using the F5 key. Then, it will select cell C5, as shown in the below screenshot.

    VBA OFFSET Example 2-1

    Output:

    VBA OFFSET Example 2-2

    Example #3

    We have seen how to offset rows and columns. We can also select the above cells from the specified cells. For example, if you are in cell A10 and want to select the A1 cell, how do you select it?

    In the case of moving down the cell, we can enter a positive number, so here in the case of moving up, we need to enter negative numbers.

    From the A9 cell, we need to move up by 8 rows, i.e., -8.

    Code:

    Sub Offset_Example1()
    
        Range("A9").Offset(-8).Select
    
    End Sub

    Negative Number Example 1

    If you run this code using the F5 key or manually run it, it will select cell A1 from the A9 cell.

    Negative Number Example 1-1

    Output:

    Negative Number Example 1-2

    Example #4

    Assume you are in cell C8. From this cell, you want to select cell A10.

    From the active cell, i.e., the C8 cell, we need to first move down 2 rows and move to the left by 2 columns to select cell A10.

    In case of moving left to select the column, we need to specify the number is negative. So, here we need to come back by -2 columns.

    Code:

    Sub Offset_Example2()
    
        Range("C8").Offset(2, -2).Select
    
    End Sub

    Negative number Example 2

    Now, run this code using the F5 key or run it manually. It will select the A10 cell as shown below:

    Negative number Example 2-1

    Output:

    Negative number Example 2-2

    Things to Remember

    • In moving up rows, we need to specify the number in negatives.
    • In case of moving left to select the column, the number should be negative.
    • A1 cell is the first row and first column.
    • The “Active Cell” means presently selected cells.
    • To select the cell using OFFSET, you need to mention “.Select.”
    • To copy the cell using OFFSET, you need to mention “.Copy.”

    Recommended Articles

    This article has been a guide to VBA OFFSET. Here, we learn how to use VBA OFFSET Property to navigate in Excel, practical examples, and a downloadable template. Below are some useful Excel articles related to VBA:-

    • Active Cell in VBA
    • VBA Set
    • What is OFFSET Formula in Excel?
    • VBA Cells References
    • VBA Format Date

    Like this post? Please share to your friends:
  • Range of dates excel
  • Range of column in excel vba
  • Range of cells in excel formula
  • Range objects in excel vba
  • Range locked vba excel