Свойство 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 |
Содержание
- Свойство Range.Offset (Excel)
- Синтаксис
- Параметры
- Пример
- Поддержка и обратная связь
- Range.Offset property (Excel)
- Syntax
- Parameters
- Example
- Support and feedback
- VBA Excel. Свойство Range.Offset
- Синтаксис
- Параметры
- Примеры
- VBA Offset Range or Cell
- Using Offset with the Range Object
- Using Offset with the Cells Object
- Selecting a Group of Cells
- VBA Coding Made Easy
- VBA Code Examples Add-in
- VBA Range Offset
- Use OFFSET with the Range Object
- Select a Range using OFFSET
- Using OFFSET with ActiveCell
- Using OFFSET with ActiveCell to Select a Range
- Copy a Range using OFFSET
- Using Cells Property with OFFSET
Свойство Range.Offset (Excel)
Возвращает объект Range, представляющий диапазон, смещенный относительно указанного диапазона.
Синтаксис
выражение.Offset (RowOffset, ColumnOffset)
выражение: переменная, представляющая объект Range.
Параметры
Имя | Обязательный или необязательный | Тип данных | Описание |
---|---|---|---|
RowOffset | Необязательный | Variant | Число строк (положительных, отрицательных или 0 (ноль), по которым диапазон должен быть смещением. Положительные значения соответствуют смещению вниз, а отрицательные — вверх. Значение по умолчанию равно 0. |
ColumnOffset | Необязательный | Variant | Число столбцов (положительных, отрицательных или 0 (ноль), по которым диапазон должен быть смещением. Положительные значения соответствуют смещению вправо, а отрицательные — влево. Значение по умолчанию равно 0. |
Пример
В этом примере активируется ячейка, расположенная на три столбца вправо и на три строки вниз от активной ячейки на листе Sheet1.
В этом примере предполагается, что Лист1 содержит таблицу со строкой заголовков. В этом примере выделяется таблица без выделения строки заголовков. Перед запуском примера активная ячейка должна находиться в любом месте таблицы.
Если RowOffset или ColumnOffset равны нулю, их можно опустить.
Выбрать ячейку D1
Выбрать ячейку A5
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Источник
Range.Offset property (Excel)
Returns a Range object that represents a range that’s offset from the specified range.
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. |
Example
This example activates the cell three columns to the right of and three rows down from the active cell on Sheet1.
This example assumes that Sheet1 contains a table that has a header row. The example selects the table, without selecting the header row. The active cell must be somewhere in the table before the example is run.
If RowOffset or ColumnOffset are 0 (zero) they can be omitted.
Support and feedback
Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.
Источник
VBA Excel. Свойство Range.Offset
Свойство Offset объекта Range, возвращающее смещенный диапазон, в том числе отдельную ячейку, в коде VBA Excel. Синтаксис, параметры, примеры.
Синтаксис
Синтаксис свойства Range.Offset:
Expression – это выражение (переменная), возвращающее исходный объект Range, относительно которого производится смещение.
Параметры
RowOffset – это параметр, задающий смещение диапазона по вертикали относительно исходного на указанное количество строк.
Значение RowOffset | Направление смещения |
---|---|
Отрицательное | вверх |
Положительное | вниз |
0 (по умолчанию) | нет смещения |
ColumnOffset – это параметр, задающий смещение диапазона по горизонтали относительно исходного на указанное число столбцов.
Значение ColumnOffset | Направление смещения |
---|---|
Отрицательное | влево |
Положительное | вправо |
0 (по умолчанию) | нет смещения |
Необходимо следить за тем, чтобы возвращаемый диапазон не вышел за пределы рабочего листа Excel. В противном случае VBA сгенерирует ошибку (Пример 3).
Примеры
Пример 1
Обращение к ячейкам, смещенным относительно ячейки A1:
Источник
VBA Offset Range or Cell
In this Article
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:
Notice the syntax:
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(“D8:D12”) is selected:
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 Code Examples Add-in
Easily access all of the code examples found on our site.
Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.
Источник
VBA Range Offset
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
- Specify the range from where you want to start.
- Enter a dot (.) to get a list of properties and methods.
- Select the offset property and specify the arguments (row and column).
- 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.
Apart from that, you can also write code to select the range using a custom size. Take an example of the following code.
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.
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.
To understand how this code works, make sure to see this explanation.
Copy a Range using OFFSET
Using Cells Property with OFFSET
You can also use the OFFSET property with the CELLS property. Consider the following code.
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.
Источник
Excel 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
- Cell reference: refers to a single cell or range of cells.
- Rows: specify the number of rows away from the given cell. If the value entered is negative, the given cell shifts to the left.
- 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!
In this Article
- ActiveCell.Offset Properties and Methods
- ActiveCell.Offset Syntax
- ActiveCell.Offset..Select
- Using Range Object with Activecell.Offset Select
- Alternatives to ActiveCell
This tutorial will demonstrate how to use Activecell Offset in VBA.
The ActiveCell is a property of VBA that represents the cell address of the active cell in your worksheet. If the cursor is positioned in cell A1 then the ActiveCell property in VBA will return the cell address of “A1”. The are a number of properties and methods that are connected to the ActiveCell. In this article we are concentrating on the ActiveCell.Offset method.
ActiveCell.Offset Properties and Methods
Activecell.Offset has a number of properties and methods available to be programmed with VBA. To view the properties and methods available, type the following statement in a procedure as shown below, and press the period key on the keyboard to see a drop down list.
Methods are depicted by the green method icon, and properties by the small hand icon. The properties and methods for the ActiveCell.Offset method are the same as for the ActiveCell method.
ActiveCell.Offset Syntax
The syntax of ActiveCell.Offset is as follows
where the RowOffset and ColumnOffset is the number of rows to offset (positive numbers for down, negative number for up) or the number of columns you wish offset (positive numbers offsets to the right, negative number to the left).
ActiveCell.Offset..Select
The Activecell.Offset..Select method is the most commonly used method for with Activecell.Offset method. It allows you to move to another cell in your worksheet. You can use this method to move across columns, or up or down rows in your worksheet.
To move down a row, but stay in the same column:
Activecell.Offset(1,0).Select
To move across a column, but stay in the same row:
Activecell.Offset (0,1).Select
To move down a row, and across a column:
Activecell.Offset (1,1).Select
To move up a row:
Activecell.Offset(-1,0).Select
To move left a column:
Activecell.Offset(0,-1).Select
In the procedure below, we are looping through a range of cells and moving down one row, and across one column as we do the loop:
Sub ActiveCellTest()
Dim x As Integer
Range("A1").Select
For x = 1 To 10
ActiveCell = x
ActiveCell.Offset(1, 1).Select
Next x
End Sub
The result of which is shown in the graphic below:
The Loop puts the value of i (1-10) into the Activecell, and then it uses the Activecell.Offset property to move down one row, and across one column to the right – repeating this loop 10 times.
Using Range Object with Activecell.Offset Select
Using the Range Object with the active cell can sometimes confuse some people.
Consider the following procedure:
Sub ActiveCellOffsetRange()
Range("B1: B10").Select
ActiveCell.Offset(1, 1).Range("A1").Select
End Sub
With the ActiveCell.Offset(1,1.Range(“A1”), the Range(“A1”) has been specified. However, this does not mean that cell A1 in the sheet will be selected. As we have specified the Range(“B1:B10”), cell A1 in that range is actually cell B1 in the workbook. Therefore the cell will be offset by 1 row and 1 column from cell B1 NOT from cell A1.
Therefore, the Range(“A1′) in this instance is not required as the macro will work the same way with it or without it.
Alternatives to ActiveCell
Instead of using Activecell with the Offset method, we can also use the Range object with the Offset method.
Sub RangeOffset()
Range("B1").Offset(0, 1).Select
End Sub
The procedure above would select cell C1 in the worksheet.
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!
Learn More!
Для движения по таблице используется функция.
переменная.Offset(RowOffset, ColumnOffset)
В качестве переменных может выступать как ячейка так и диапазон (Range) удобно пользоваться этой функцией для смещения относительно текущей ячейки.
Например, смещение ввниз на одну ячейку и выделение ее:
ActiveCell.Offset(1, 0).Select
Если нужно двигаться вверх, то нужно использовать отрицательное число:
ActiveCell.Offset(-1, 0).Select
Функция ниже использует эту возможность для того, чтобы пробежаться вниз до первой пустой ячейки.
Sub beg() Dim a As Boolean Dim d As Double Dim c As Range a = True Set c = Range(ActiveCell.address) c.Select d = c.Value c.Value = d While (a = True) ActiveCell.Offset(1, 0).Select If (IsEmpty(ActiveCell.Value) = False) Then Set c = Range(ActiveCell.address) c.Select d = c.Value c.Value = d Else a = False End If Wend End Sub