Range with offset excel

Excel for Microsoft 365 Excel for Microsoft 365 for Mac Excel for the web Excel 2021 Excel 2021 for Mac Excel 2019 Excel 2019 for Mac Excel 2016 Excel 2016 for Mac Excel 2013 Excel 2010 Excel 2007 Excel for Mac 2011 Excel Starter 2010 More…Less

This article describes the formula syntax and usage of the OFFSET function in Microsoft Excel.

Description

Returns a reference to a range that is a specified number of rows and columns from a cell or range of cells. The reference that is returned can be a single cell or a range of cells. You can specify the number of rows and the number of columns to be returned.

Syntax

OFFSET(reference, rows, cols, [height], [width])

The OFFSET function syntax has the following arguments:

  • Reference    Required. The reference from which you want to base the offset. Reference must refer to a cell or range of adjacent cells; otherwise, OFFSET returns the #VALUE! error value.

  • Rows    Required. The number of rows, up or down, that you want the upper-left cell to refer to. Using 5 as the rows argument specifies that the upper-left cell in the reference is five rows below reference. Rows can be positive (which means below the starting reference) or negative (which means above the starting reference).

  • Cols    Required. The number of columns, to the left or right, that you want the upper-left cell of the result to refer to. Using 5 as the cols argument specifies that the upper-left cell in the reference is five columns to the right of reference. Cols can be positive (which means to the right of the starting reference) or negative (which means to the left of the starting reference).

  • Height    Optional. The height, in number of rows, that you want the returned reference to be. Height must be a positive number.

  • Width    Optional. The width, in number of columns, that you want the returned reference to be. Width must be a positive number.

Remarks

  • If rows and cols offset reference over the edge of the worksheet, OFFSET returns the #REF! error value.

  • If height or width is omitted, it is assumed to be the same height or width as reference.

  • OFFSET doesn’t actually move any cells or change the selection; it just returns a reference. OFFSET can be used with any function expecting a reference argument. For example, the formula SUM(OFFSET(C2,1,2,3,1)) calculates the total value of a 3-row by 1-column range that is 1 row below and 2 columns to the right of cell C2.

Example

Copy the example data in the following table, and paste it in cell A1 of a new Excel worksheet. For formulas to show results, select them, press F2, and then press Enter. If you need to, you can adjust the column widths to see all the data.

Formula

Description

Result

=OFFSET(D3,3,-2,1,1)

Displays the value in cell B6 (4)

4

=SUM(OFFSET(D3:F5,3,-2, 3, 3))

Sums the range B6:D8

34

=OFFSET(D3, -3, -3)

Returns an error, because the reference is to a non-existent range on the worksheet.

#REF!

Data

Data

4

10

8

3

3

6

Need more help?

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

The Excel OFFSET function returns a dynamic range constructed with five inputs: (1) a starting point, (2) a row offset, (3) a column offset, (4) a height in rows, (5) a width in columns.

OFFSET is a volatile function, and can cause performance issues in large or complex worksheets.

The starting point (the reference argument) can be one cell or a range of cells. The rows and cols arguments are the number of cells to «offset» from the starting point. The height and width arguments are optional and determine the size of the range that is created. When height and width are omitted, they default to the height and width of reference.

For example, to reference C5 starting at A1,  reference is A1, rows is 4 and cols is 2:

=OFFSET(A1,4,2) // returns reference to C5

To reference C1:C5 from A1, reference is A1, rows is 0, cols is 2, height is 5, and width is 1:

=OFFSET(A1,0,2,5,1) // returns reference to C1:C5

Note: width could be omitted, since it will default to 1.

It is common to see OFFSET wrapped in another function that expects a range. For example, to SUM C1:C5, beginning at A1:

=SUM(OFFSET(A1,0,2,5,1)) // SUM C1:C5

The main purpose of OFFSET is to allow formulas to dynamically adjust to available data or to user input. The OFFSET function can be used to build a dynamic named range for charts or pivot tables, to ensure that source data is always up to date.

Note: Excel documentation states height and width can’t be negative, but negative values appear to have worked fine since the early 1990’s. The OFFSET function in Google Sheets won’t allow a negative value for height or width arguments.

Examples

The examples below show how OFFSET can be configured to return different kinds of ranges. These screens were taken with Excel 365, so OFFSET returns a dynamic array when the result is more than one cell. In older versions of Excel, you can use the F9 key to check results returned from OFFSET.

Example #1

In the screen below, we use OFFSET to return the third value (March) in the second column (West). The formula in H4 is:

=OFFSET(B3,3,2) // returns D6

OFFSET Function Example 1

Example #2

In the screen below, we use OFFSET to return the last value (June) in the third column (North). The formula in H4 is:

=OFFSET(B3,6,3) // returns E9

OFFSET Function Example 2

Example #3

Below, we use OFFSET to return all values in the third column (North). The formula in H4 is:

=OFFSET(B3,1,3,6) // returns E4:E9

OFFSET Function Example 3

Example #4

Below, we use OFFSET to return all values for May (fifth row). The formula in H4 is:

=OFFSET(B3,5,1,1,4) // returns C8:F8

OFFSET Function Example 4

Example #5

Below, we use OFFSET to return April, May, and June values for the West region. The formula in H4 is:

=OFFSET(B3,4,2,3,1) // returns D7:D9

OFFSET Function Example 5

Example #6

Below, we use OFFSET to return April, May, and June values for West and North. The formula in H4 is:

=OFFSET(B3,4,2,3,2) // returns D7:E9

OFFSET Function Example 6

Notes

  • OFFSET only returns a reference, no cells are moved.
  • Both rows and cols can be supplied as negative numbers to reverse their normal offset direction — negative cols offset to the left, and negative rows offset above.
  • OFFSET is a «volatile function». Volatile functions can make larger and more complex workbooks run slowly.
  • OFFSET will display the #REF! error value if the offset is outside the edge of the worksheet.
  • When height or width is omitted, the height and width of reference is used.
  • OFFSET can be used with any other function that expects to receive a reference.
  • Excel documentation says height and width can’t be negative, but negative values do work.

Содержание

  1. OFFSET function
  2. Description
  3. Syntax
  4. Remarks
  5. Example
  6. Свойство Range.Offset (Excel)
  7. Синтаксис
  8. Параметры
  9. Пример
  10. Поддержка и обратная связь
  11. How to create a dynamic named range with OFFSET
  12. Related functions
  13. Transcript
  14. VBA Excel. Свойство Range.Offset
  15. Синтаксис
  16. Параметры
  17. Примеры
  18. OFFSET Function
  19. Related functions
  20. Summary
  21. Purpose
  22. Return value
  23. Arguments
  24. Syntax
  25. Usage notes
  26. Examples
  27. Example #1
  28. Example #2
  29. Example #3
  30. Example #4
  31. Example #5
  32. Example #6

OFFSET function

This article describes the formula syntax and usage of the OFFSET function in Microsoft Excel.

Description

Returns a reference to a range that is a specified number of rows and columns from a cell or range of cells. The reference that is returned can be a single cell or a range of cells. You can specify the number of rows and the number of columns to be returned.

Syntax

OFFSET(reference, rows, cols, [height], [width])

The OFFSET function syntax has the following arguments:

Reference Required. The reference from which you want to base the offset. Reference must refer to a cell or range of adjacent cells; otherwise, OFFSET returns the #VALUE! error value.

Rows Required. The number of rows, up or down, that you want the upper-left cell to refer to. Using 5 as the rows argument specifies that the upper-left cell in the reference is five rows below reference. Rows can be positive (which means below the starting reference) or negative (which means above the starting reference).

Cols Required. The number of columns, to the left or right, that you want the upper-left cell of the result to refer to. Using 5 as the cols argument specifies that the upper-left cell in the reference is five columns to the right of reference. Cols can be positive (which means to the right of the starting reference) or negative (which means to the left of the starting reference).

Height Optional. The height, in number of rows, that you want the returned reference to be. Height must be a positive number.

Width Optional. The width, in number of columns, that you want the returned reference to be. Width must be a positive number.

If rows and cols offset reference over the edge of the worksheet, OFFSET returns the #REF! error value.

If height or width is omitted, it is assumed to be the same height or width as reference.

OFFSET doesn’t actually move any cells or change the selection; it just returns a reference. OFFSET can be used with any function expecting a reference argument. For example, the formula SUM(OFFSET(C2,1,2,3,1)) calculates the total value of a 3-row by 1-column range that is 1 row below and 2 columns to the right of cell C2.

Example

Copy the example data in the following table, and paste it in cell A1 of a new Excel worksheet. For formulas to show results, select them, press F2, and then press Enter. If you need to, you can adjust the column widths to see all the data.

Источник

Свойство 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 и обратная связь.

Источник

How to create a dynamic named range with OFFSET

Transcript

In this video we’re going to look at how to create a dynamic named range using the OFFSET function.

To create a dynamic named range that refers to this data using the OFFSET function, first identify the first cell of the data in the upper left. In this case, that’s cell B6.

To create a named range, we’re going to use the Name Manager. However, it will be easier to enter the formula using the formula bar, so I’ll start by entering the OFFSET function in cell K6, and then use that formula to create a named range in the next step.

The OFFSET function takes five arguments: reference, rows, columns, height, and width. In this case the reference, or starting point, is cell B6, which we want to make absolute. When you’re creating dynamic named ranges, you must use absolute references.

We don’t want any offset for rows and columns, so both of these arguments are «0».

However, we do need to provide a height and width. To reference the full set of data, we need to provide a height of 10 rows and a width of 8 columns.

If I enter the OFFSET formula as-is we’ll get a VALUE error, since it’s returning a range which, in this case, is an array of cells. However, if I evaluate the formula with F9, you can see that the array is there.

Now let’s use this formula to make the dynamic named range. I do that by copying the formula and then creating a new name that uses this formula for the reference.

When you’re working with dynamic ranges based on formulas, a good tip to remember is that you can get Excel to show you the range on the worksheet by clicking out of the reference area, and back again. If the moving dashed lines are not in the right place, you know that there’s something wrong with the formula.

So, we now have a named range based on OFFSET, but it’s not dynamic yet. If I add properties to the bottom of the list, they aren’t included.

To make the range dynamic, we need to make the height dynamic. We can do that by using the COUNTA function in place of the hard-coded value «10».

I’ll assume, in this case, that we won’t have any more than 20 properties in the list, so I’ll use the range B6:B25 inside COUNTA.

COUNTA counts non-empty cells, so it’s important to use it on a column that always contains values. Otherwise, you’ll get inconsistent results.

Now, if I paste new data below, the range expands to include it.

If you want to make the width of this range dynamic as well, you can follow the same approach that we used for height, counting non-empty cells in a range that includes the table header.

Dynamic ranges that use OFFSET work well, but remember that OFFSET is a volatile formula that will recalculate whenever changes are made to the worksheet. For a smaller table, this won’t cause any performance issues, but if you’re working with a lot of data, you may want to use INDEX or Excel’s built in Table feature to create the Dynamic range.

Источник

VBA Excel. Свойство Range.Offset

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

Синтаксис

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

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

Параметры

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

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

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

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

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

Примеры

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

Источник

OFFSET Function

Summary

The Excel OFFSET function returns a reference to a range constructed with five inputs: (1) a starting point, (2) a row offset, (3) a column offset, (4) a height in rows, (5) a width in columns. OFFSET is handy in formulas that require a dynamic range.

Purpose

Return value

Arguments

  • reference — The starting point, supplied as a cell reference or range.
  • rows — The number of rows to offset below the starting reference.
  • cols — The number of columns to offset to the right of the starting reference.
  • height — [optional] The height in rows of the returned reference.
  • width — [optional] The width in columns of the returned reference.

Syntax

Usage notes

The Excel OFFSET function returns a dynamic range constructed with five inputs: (1) a starting point, (2) a row offset, (3) a column offset, (4) a height in rows, (5) a width in columns.

The starting point (the reference argument) can be one cell or a range of cells. The rows and cols arguments are the number of cells to «offset» from the starting point. The height and width arguments are optional and determine the size of the range that is created. When height and width are omitted, they default to the height and width of reference.

For example, to reference C5 starting at A1, reference is A1, rows is 4 and cols is 2:

To reference C1:C5 from A1, reference is A1, rows is 0, cols is 2, height is 5, and width is 1:

Note: width could be omitted, since it will default to 1.

It is common to see OFFSET wrapped in another function that expects a range. For example, to SUM C1:C5, beginning at A1:

The main purpose of OFFSET is to allow formulas to dynamically adjust to available data or to user input. The OFFSET function can be used to build a dynamic named range for charts or pivot tables, to ensure that source data is always up to date.

Note: Excel documentation states height and width can’t be negative, but negative values appear to have worked fine since the early 1990’s. The OFFSET function in Google Sheets won’t allow a negative value for height or width arguments.

Examples

The examples below show how OFFSET can be configured to return different kinds of ranges. These screens were taken with Excel 365, so OFFSET returns a dynamic array when the result is more than one cell. In older versions of Excel, you can use the F9 key to check results returned from OFFSET.

Example #1

In the screen below, we use OFFSET to return the third value (March) in the second column (West). The formula in H4 is:

Example #2

In the screen below, we use OFFSET to return the last value (June) in the third column (North). The formula in H4 is:

Example #3

Below, we use OFFSET to return all values in the third column (North). The formula in H4 is:

Example #4

Below, we use OFFSET to return all values for May (fifth row). The formula in H4 is:

Example #5

Below, we use OFFSET to return April, May, and June values for the West region. The formula in H4 is:

Example #6

Below, we use OFFSET to return April, May, and June values for West and North. The formula in H4 is:

Источник

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

    Like this post? Please share to your friends:
  • Range with excel in visual basic
  • Range with address excel
  • Range vba excel синтаксис
  • Range vba excel примеры
  • Range vba excel несколько диапазонов