Excel vba offset one row

Свойство 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

    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

    # Ways to refer to a single cell

    The simplest way to refer to a single cell on the current Excel worksheet is simply to enclose the A1 form of its reference in square brackets:

    Note that square brackets are just convenient syntactic sugar (opens new window) for the Evaluate method of the Application object, so technically, this is identical to the following code:

    You could also call the Cells method which takes a row and a column and returns a cell reference.

    Remember that whenever you pass a row and a column to Excel from VBA, the row is always first, followed by the column, which is confusing because it is the opposite of the common A1 notation where the column appears first.

    In both of these examples, we did not specify a worksheet, so Excel will use the active sheet (the sheet that is in front in the user interface). You can specify the active sheet explicitly:

    Or you can provide the name of a particular sheet:

    There are a wide variety of methods that can be used to get from one range to another. For example, the Rows method can be used to get to the individual rows of any range, and the Cells method can be used to get to individual cells of a row or column, so the following code refers to cell C1:

    # Creating a Range

    A Range (opens new window) cannot be created or populated the same way a string would:

    It is considered best practice to qualify your references (opens new window), so from now on we will use the same approach here.
    More about Creating Object Variables (e.g. Range) on MSDN (opens new window) . More about Set Statement on MSDN (opens new window).

    There are different ways to create the same Range:

    Note in the example that Cells(2, 1) is equivalent to Range(«A2»). This is because Cells returns a Range object.
    Some sources: Chip Pearson-Cells Within Ranges (opens new window); MSDN-Range Object (opens new window); John Walkenback-Referring To Ranges In Your VBA Code (opens new window).

    Also note that in any instance where a number is used in the declaration of the range, and the number itself is outside of quotation marks, such as Range(«A» & 2), you can swap that number for a variable that contains an integer/long. For example:

    If you are using double loops, Cells is better:

    # Offset Property

    • Offset(Rows, Columns) — The operator used to statically reference another point from the current cell. Often used in loops. It should be understood that positive numbers in the rows section moves right, wheres as negatives move left. With the columns section positives move down and negatives move up.

    i.e

    This code selects B2, puts a new string there, then moves that string back to A1 afterwards clearing out B2.

    # Saving a reference to a cell in a variable

    To save a reference to a cell in a variable, you must use the Set syntax, for example:

    later…

    Why is the Set keyword required? Set tells Visual Basic that the value on the right hand side of the = is meant to be an object.

    # How to Transpose Ranges (Horizontal to Vertical & vice versa)

    Note: Copy/PasteSpecial also has a Paste Transpose option which updates the transposed cells’ formulas as well.

    # Syntax

    • Set — The operator used to set a reference to an object, such as a Range
    • For Each — The operator used to loop through every item in a collection

    Note that the variable names r, cell and others can be named however you like but should be named appropriately so the code is easier to understand for you and others.

    excelvbatutorialExcel is the most commonly used spreadsheet management software. VBA , or Visual Basic for Applications, takes it a step further and makes it easy for you to automate just about anything in Excel (check out this tutorial for a quick into to VBA). In today’s tutorial, we’re going to show you how to use the Offset function in VBA, to select a cell or a range of cells. You require basic familiarity with both Excel and VBA.

    If you’re new to them, no problem, you can try out our course for VBA with Excel.

    What is the Offset Function

    The OffSet() returns the value of the cell, at an offset that you’ve specified.  The syntax of this function looks like this:

     OffSet(Cell reference, rows, columns, height, width)

    Here’s what each parameter means

    1. Cell reference: refers to a single cell or range of cells.
    2. Rows: specify the number of rows away from the given cell. If the value entered is negative, the given cell shifts to the left.
    3. Columns: specify the number of columns away from the given cell. If value is negative, the cell shifts up.

    Note that height and width are optional. They are used to specify the height and width of the returned range in cells. You can insert the OffSet() formula in any cell in the worksheet, except obviously, the cells from which you want the offset.

    Combining Range() with OffSet()

    The OffSet property is usually used in tandem with the Range property to specify a new location. Let’s take a look at this example

    Range("B1").Offset(RowOffSet:=1, ColumnOffset:=1).Select

    This code will select C2. The parameter RowOffSet is used to move 1 row from cell B1. Similarly, the parameter ColumnOffSet is used to move 1 column from cell B1. Note that the parameters have to be separated by a comma.

    An easier way to accomplish the same result is to use a shorthand method, like we show below

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

    Here we only specified the numbers for the row and column offset. VBA will internally “know” that the first one is for the row offset, while the second one is for the column offset.  If you’d like to explore the Range() function more, you can take a look at our course on VBA macros. Now, let’s move on to some more examples.

    How to Specify Only Rows

    It’s possible to specify just the rows and not the columns. Here’s how you can do it.

     Range("B1").Offset(1).Select

    Here we’ve omitted the column parameter and its comma. This code results in only moving 1 row down from the original cell location. It will select the entire row, not just a single cell.

    How to Specify Only Columns

    Similarly it’s possible to just specify the columns and omit the rows. The code will look like this:

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

    The comma is necessary for Excel to know that only column offset has been set.

    How to Specify Negative OffSet

    Can you guess how to do this? It’s simple enough. Here’s the code

    Range("D2").Offset(-1, -1 ).Select

    This makes the selection go up 1 row and 1 column from the starting position. That is from cell D2 we move up to cell C1.

    How to OffSet a Range of Cells

    It is also possible to specify more than one cell for the Range. Say you want to select or get the offset for a range of cells

    Range("B1:D4").Offset(1, 1).Select

    Here, we start off with the range of cells from B1 to D4. The objective is to offset this complete range of cells by 1 row and 1 column. The new range of cells will be from C2 to E5.

    Combining Active Cell with Offset

    The active cell refers to the currently selected cell. Let’s check a few examples that involve active cells. Here is the code to move one cell down from the currently selected cells is

     ActiveCell.Offset(1,0).Select

    Combining Active Cell with Range() and Offset()

    The following code selects a cell in addition to four more to the right which are to be copied/pasted in another location.

     Range(ActiveCell,ActiveCell.Offset(0,4)).Copy

    Take note that there is a comma after the first ActiveCell instance and a double closing parenthesis before the Copy. Let us now  move on to cover simple programs that use OffSet functionality to obtain desired results.

    Example 1: To Count the Rows in an Excel Worksheet

    Sub CountNumRows()
    Dim Count1 as Long
    Count1 = 0
    Do
    Count1 = Count1 + 1
    ActiveCell.Offset(1, 0).Select
    Loop Until IsEmpty(ActiveCell.Offset(0, 1))
    MsgBox "There are" Count1 "Rows"
    End Sub

    In this program, we declared Count1 as a variable of type long. Count is incremented by 1. Then OffSet() is used to loop through the rows. When an empty row is encountered the loop terminates. The variable count1 contains the total number of rows.MsgBox() displays a pop-up box with the total number of rows.

    Example 2: Combining Range with OffSet to Fill a Range of Cells with Even Numbers from 1 to 100.

    Sub prog1()
    Dim Num
    Num = 0
    For Row = 0 To 9
    For Col = 0 To 9
    Range(“A1”).Offset(Row, Col).Value = Num
    Num = Num + 2
    Next Col
    Next Row
    End Sub

    In this program, A1 is the given cell and the resultant range is from A1 to J10. Variable Num is initialized to zero and is incremented by the value 2 each time in the loop. The resultant range of cells contain each and every even number without duplicates from 1 to 100.

    Hope you found the offset function useful, and can now use it in your own programs.  We have just covered the tip of the iceberg. There’s lots more to it. You can check out more details with this ultimate VBA course, and if you’d like to hop over to advanced Macros we just the right course with Mr Excel!

    Like this post? Please share to your friends:
  • Excel vba for end for
  • Excel vba line input
  • Excel vba like and not like
  • Excel vba for each row in range
  • Excel vba left описание