When you move or copy rows and columns, by default Excel moves or copies all data that they contain, including formulas and their resulting values, comments, cell formats, and hidden cells.
When you copy cells that contain a formula, the relative cell references are not adjusted. Therefore, the contents of cells and of any cells that point to them might display the #REF! error value. If that happens, you can adjust the references manually. For more information, see Detect errors in formulas.
You can use the Cut command or Copy command to move or copy selected cells, rows, and columns, but you can also move or copy them by using the mouse.
By default, Excel displays the Paste Options button. If you need to redisplay it, go to Advanced in Excel Options. For more information, see Advanced options.
-
Select the cell, row, or column that you want to move or copy.
-
Do one of the following:
-
To move rows or columns, on the Home tab, in the Clipboard group, click Cut or press CTRL+X.
-
To copy rows or columns, on the Home tab, in the Clipboard group, click Copy or press CTRL+C.
-
-
Right-click a row or column below or to the right of where you want to move or copy your selection, and then do one of the following:
-
When you are moving rows or columns, click Insert Cut Cells.
-
When you are copying rows or columns, click Insert Copied Cells.
Tip: To move or copy a selection to a different worksheet or workbook, click another worksheet tab or switch to another workbook, and then select the upper-left cell of the paste area.
-
Note: Excel displays an animated moving border around cells that were cut or copied. To cancel a moving border, press Esc.
By default, drag-and-drop editing is turned on so that you can use the mouse to move and copy cells.
-
Select the row or column that you want to move or copy.
-
Do one of the following:
-
Cut and replace
Point to the border of the selection. When the pointer becomes a move pointer , drag the rows or columns to another location. Excel warns you if you are going to replace a column. Press Cancel to avoid replacing. -
Copy and replace Hold down CTRL while you point to the border of the selection. When the pointer becomes a copy pointer , drag the rows or columns to another location. Excel doesn’t warn you if you are going to replace a column. Press CTRL+Z if you don’t want to replace a row or column.
-
Cut and insert Hold down SHIFT while you point to the border of the selection. When the pointer becomes a move pointer , drag the rows or columns to another location.
-
Copy and insert Hold down SHIFT and CTRL while you point to the border of the selection. When the pointer becomes a move pointer , drag the rows or columns to another location.
Note: Make sure that you hold down CTRL or SHIFT during the drag-and-drop operation. If you release CTRL or SHIFT before you release the mouse button, you will move the rows or columns instead of copying them.
-
Note: You cannot move or copy nonadjacent rows and columns by using the mouse.
If some cells, rows, or columns on the worksheet are not displayed, you have the option of copying all cells or only the visible cells. For example, you can choose to copy only the displayed summary data on an outlined worksheet.
-
Select the row or column that you want to move or copy.
-
On the Home tab, in the Editing group, click Find & Select, and then click Go To Special.
-
Under Select, click Visible cells only, and then click OK.
-
On the Home tab, in the Clipboard group, click Copy or press Ctrl+C. .
-
Select the upper-left cell of the paste area.
Tip: To move or copy a selection to a different worksheet or workbook, click another worksheet tab or switch to another workbook, and then select the upper-left cell of the paste area.
-
On the Home tab, in the Clipboard group, click Paste or press Ctrl+V.
If you click the arrow below Paste , you can choose from several paste options to apply to your selection.
Excel pastes the copied data into consecutive rows or columns. If the paste area contains hidden rows or columns, you might have to unhide the paste area to see all of the copied cells.
When you copy or paste hidden or filtered data to another application or another instance of Excel, only visible cells are copied.
-
Select the row or column that you want to move or copy.
-
On the Home tab, in the Clipboard group, click Copy or press Ctrl+C.
-
Select the upper-left cell of the paste area.
-
On the Home tab, in the Clipboard group, click the arrow below Paste , and then click Paste Special.
-
Select the Skip blanks check box.
-
Double-click the cell that contains the data that you want to move or copy. You can also edit and select cell data in the formula bar.
-
Select the row or column that you want to move or copy.
-
On the Home tab, in the Clipboard group, do one of the following:
-
To move the selection, click Cut or press Ctrl+X.
-
To copy the selection, click Copy or press Ctrl+C.
-
-
In the cell, click where you want to paste the characters, or double-click another cell to move or copy the data.
-
On the Home tab, in the Clipboard group, click Paste or press Ctrl+V.
-
Press ENTER.
Note: When you double-click a cell or press F2 to edit the active cell, the arrow keys work only within that cell. To use the arrow keys to move to another cell, first press Enter to complete your editing changes to the active cell.
When you paste copied data, you can do any of the following:
-
Paste only the cell formatting, such as font color or fill color (and not the contents of the cells).
-
Convert any formulas in the cell to the calculated values without overwriting the existing formatting.
-
Paste only the formulas (and not the calculated values).
Procedure
-
Select the row or column that you want to move or copy.
-
On the Home tab, in the Clipboard group, click Copy or press Ctrl+C.
-
Select the upper-left cell of the paste area or the cell where you want to paste the value, cell format, or formula.
-
On the Home tab, in the Clipboard group, click the arrow below Paste , and then do one of the following:
-
To paste values only, click Values.
-
To paste cell formats only, click Formatting.
-
To paste formulas only, click Formulas.
-
When you paste copied data, the pasted data uses the column width settings of the target cells. To correct the column widths so that they match the source cells, follow these steps.
-
Select the row or column that you want to move or copy.
-
On the Home tab, in the Clipboard group, do one of the following:
-
To move cells, click Cut or press Ctrl+X.
-
To copy cells, click Copy or press Ctrl+C.
-
-
Select the upper-left cell of the paste area.
Tip: To move or copy a selection to a different worksheet or workbook, click another worksheet tab or switch to another workbook, and then select the upper-left cell of the paste area.
-
On the Home tab, in the Clipboard group, click the arrow under Paste , and then click Keep Source Column Widths.
You can use the Cut command or Copy command to move or copy selected cells, rows, and columns, but you can also move or copy them by using the mouse.
-
Select the cell, row, or column that you want to move or copy.
-
Do one of the following:
-
To move rows or columns, on the Home tab, in the Clipboard group, click Cut or press CTRL+X.
-
To copy rows or columns, on the Home tab, in the Clipboard group, click Copy or press CTRL+C.
-
-
Right-click a row or column below or to the right of where you want to move or copy your selection, and then do one of the following:
-
When you are moving rows or columns, click Insert Cut Cells.
-
When you are copying rows or columns, click Insert Copied Cells.
Tip: To move or copy a selection to a different worksheet or workbook, click another worksheet tab or switch to another workbook, and then select the upper-left cell of the paste area.
-
Note: Excel displays an animated moving border around cells that were cut or copied. To cancel a moving border, press Esc.
-
Select the row or column that you want to move or copy.
-
Do one of the following:
-
Cut and insert
Point to the border of the selection. When the pointer becomes a hand pointer , drag the row or column to another location -
Cut and replace Hold down SHIFT while you point to the border of the selection. When the pointer becomes a move pointer , drag the row or column to another location. Excel warns you if you are going to replace a row or column. Press Cancel to avoid replacing.
-
Copy and insert Hold down CTRL while you point to the border of the selection. When the pointer becomes a move pointer , drag the row or column to another location.
-
Copy and replace Hold down SHIFT and CTRL while you point to the border of the selection. When the pointer becomes a move pointer , drag the row or column to another location. Excel warns you if you are going to replace a row or column. Press Cancel to avoid replacing.
Note: Make sure that you hold down CTRL or SHIFT during the drag-and-drop operation. If you release CTRL or SHIFT before you release the mouse button, you will move the rows or columns instead of copying them.
-
Note: You cannot move or copy nonadjacent rows and columns by using the mouse.
-
Double-click the cell that contains the data that you want to move or copy. You can also edit and select cell data in the formula bar.
-
Select the row or column that you want to move or copy.
-
On the Home tab, in the Clipboard group, do one of the following:
-
To move the selection, click Cut or press Ctrl+X.
-
To copy the selection, click Copy or press Ctrl+C.
-
-
In the cell, click where you want to paste the characters, or double-click another cell to move or copy the data.
-
On the Home tab, in the Clipboard group, click Paste or press Ctrl+V.
-
Press ENTER.
Note: When you double-click a cell or press F2 to edit the active cell, the arrow keys work only within that cell. To use the arrow keys to move to another cell, first press Enter to complete your editing changes to the active cell.
When you paste copied data, you can do any of the following:
-
Paste only the cell formatting, such as font color or fill color (and not the contents of the cells).
-
Convert any formulas in the cell to the calculated values without overwriting the existing formatting.
-
Paste only the formulas (and not the calculated values).
Procedure
-
Select the row or column that you want to move or copy.
-
On the Home tab, in the Clipboard group, click Copy or press Ctrl+C.
-
Select the upper-left cell of the paste area or the cell where you want to paste the value, cell format, or formula.
-
On the Home tab, in the Clipboard group, click the arrow below Paste , and then do one of the following:
-
To paste values only, click Paste Values.
-
To paste cell formats only, click Paste Formatting.
-
To paste formulas only, click Paste Formulas.
-
You can move or copy selected cells, rows, and columns by using the mouse and Transpose.
-
Select the cells or range of cells that you want to move or copy.
-
Point to the border of the cell or range that you selected.
-
When the pointer becomes a , do one of the following:
To |
Do this |
---|---|
Move cells |
Drag the cells to another location. |
Copy cells |
Hold down OPTION and drag the cells to another location. |
Note: When you drag or paste cells to a new location, if there is pre-existing data in that location, Excel will overwrite the original data.
-
Select the rows or columns that you want to move or copy.
-
Point to the border of the cell or range that you selected.
-
When the pointer becomes a , do one of the following:
To |
Do this |
---|---|
Move rows or columns |
Drag the rows or columns to another location. |
Copy rows or columns |
Hold down OPTION and drag the rows or columns to another location. |
Move or copy data between existing rows or columns |
Hold down SHIFT and drag your row or column between existing rows or columns. Excel makes space for the new row or column. |
-
Copy the rows or columns that you want to transpose.
-
Select the destination cell (the first cell of the row or column into which you want to paste your data) for the rows or columns that you are transposing.
-
On the Home tab, under Edit, click the arrow next to Paste, and then click Transpose.
Note: Columns and rows cannot overlap. For example, if you select values in Column C, and try to paste them into a row that overlaps Column C, Excel displays an error message. The destination area of a pasted column or row must be outside the original values.
See also
Insert or delete cells, rows, columns
Содержание
- Move or copy cells, rows, and columns
- VBA Copy / Paste Rows & Columns
- Rows & Columns – Paste vs. Insert
- Copy & Paste Over Existing Row / Column
- Copy & Insert Row / Column
- Copy Entire Row
- Cut and Paste Rows
- Copy Multiple Rows
- VBA Coding Made Easy
- Copy Entire Column
- Cut and Paste Columns
- Copy Multiple Columns
- Copy Rows or Columns to Another Sheet
- Cut Rows or Columns to Another Sheet
- VBA Code Examples Add-in
- VBA Excel. Вырезание, копирование и вставка ячеек (диапазонов)
- Метод Range.Cut
- Синтаксис
- Параметры
- Метод Range.Copy
- Синтаксис
- Параметры
- Метод Worksheet.Paste
- Синтаксис
- Параметры
- Примеры
- 43 комментария для “VBA Excel. Вырезание, копирование и вставка ячеек (диапазонов)”
Move or copy cells, rows, and columns
When you move or copy rows and columns, by default Excel moves or copies all data that they contain, including formulas and their resulting values, comments, cell formats, and hidden cells.
When you copy cells that contain a formula, the relative cell references are not adjusted. Therefore, the contents of cells and of any cells that point to them might display the #REF! error value. If that happens, you can adjust the references manually. For more information, see Detect errors in formulas.
You can use the Cut command or Copy command to move or copy selected cells, rows, and columns, but you can also move or copy them by using the mouse.
By default, Excel displays the Paste Options button. If you need to redisplay it, go to Advanced in Excel Options. For more information, see Advanced options.
Select the cell, row, or column that you want to move or copy.
Do one of the following:
To move rows or columns, on the Home tab, in the Clipboard group, click Cut or press CTRL+X.
To copy rows or columns, on the Home tab, in the Clipboard group, click Copy or press CTRL+C.
Right-click a row or column below or to the right of where you want to move or copy your selection, and then do one of the following:
When you are moving rows or columns, click Insert Cut Cells.
When you are copying rows or columns, click Insert Copied Cells.
Tip: To move or copy a selection to a different worksheet or workbook, click another worksheet tab or switch to another workbook, and then select the upper-left cell of the paste area.
Note: Excel displays an animated moving border around cells that were cut or copied. To cancel a moving border, press Esc.
By default, drag-and-drop editing is turned on so that you can use the mouse to move and copy cells.
Select the row or column that you want to move or copy.
Do one of the following:
Cut and replace Point to the border of the selection. When the pointer becomes a move pointer , drag the rows or columns to another location. Excel warns you if you are going to replace a column. Press Cancel to avoid replacing.
Copy and replace Hold down CTRL while you point to the border of the selection. When the pointer becomes a copy pointer , drag the rows or columns to another location. Excel doesn’t warn you if you are going to replace a column. Press CTRL+Z if you don’t want to replace a row or column.
Cut and insert Hold down SHIFT while you point to the border of the selection. When the pointer becomes a move pointer , drag the rows or columns to another location.
Copy and insert Hold down SHIFT and CTRL while you point to the border of the selection. When the pointer becomes a move pointer , drag the rows or columns to another location.
Note: Make sure that you hold down CTRL or SHIFT during the drag-and-drop operation. If you release CTRL or SHIFT before you release the mouse button, you will move the rows or columns instead of copying them.
Note: You cannot move or copy nonadjacent rows and columns by using the mouse.
Источник
VBA Copy / Paste Rows & Columns
In this Article
This tutorial will teach you how to copy (or cut) entire Rows or Columns using VBA. We cover copying and pasting ranges of cells in another article.
First we will show you how to paste or insert copied rows/columns and discuss the differences. Then we will show you all of the different ways to references rows and columns when copying or cutting.
Rows & Columns – Paste vs. Insert
When pasting rows and columns you have two options: You can paste over the existing row (or column) or you can insert a new row (or column).
Let’s look at the difference…
Copy & Paste Over Existing Row / Column
This will copy row 1 and paste it into the existing row 5:
This will copy column C and paste it into column E:
Copy & Insert Row / Column
Instead you can insert the copied row or column and shift the existing rows or columns to make room.
This will copy row 1 and insert it into row 5, shifting the existing rows down:
This will copy column C and insert it into column E, shifting the existing columns to the right:
Copy Entire Row
Below we will show you several ways to copy row 1 and paste into row 5.
Cut and Paste Rows
Simply use Cut instead of Copy to cut and paste rows:
Copy Multiple Rows
Here are examples of copying multiple rows at once:
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!
Copy Entire Column
You can copy entire columns similarily to copying entire rows:
Cut and Paste Columns
Simply use Cut instead of Copy to cut and paste columns:
Copy Multiple Columns
Here are examples of copying multiple columns at once:
Copy Rows or Columns to Another Sheet
To copy to another sheet, simply use the Sheet Object:
Cut Rows or Columns to Another Sheet
You can use the exact same technique to cut and paste rows or columns to another sheet.
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 Excel. Вырезание, копирование и вставка ячеек (диапазонов)
Вырезание, перемещение, копирование и вставка ячеек (диапазонов) в VBA Excel. Методы Cut, Copy и PasteSpecial объекта Range, метод Paste объекта Worksheet.
Метод Range.Cut
Синтаксис
Параметры
Параметры | Описание |
---|---|
Destination | Необязательный параметр. Диапазон ячеек рабочего листа, в который будет вставлен (перемещен) вырезанный объект Range (достаточно указать верхнюю левую ячейку диапазона). Если этот параметр опущен, объект вырезается в буфер обмена. |
Для вставки на рабочий лист диапазона ячеек, вырезанного в буфер обмена методом Range.Cut, следует использовать метод Worksheet.Paste.
Метод Range.Copy
Синтаксис
Параметры
Параметры | Описание |
---|---|
Destination | Необязательный параметр. Диапазон ячеек рабочего листа, в который будет вставлен скопированный объект Range (достаточно указать верхнюю левую ячейку диапазона). Если этот параметр опущен, объект копируется в буфер обмена. |
Метод Worksheet.Paste
Синтаксис
Метод Worksheet.Paste работает как с диапазонами ячеек, вырезанными в буфер обмена методом Range.Cut, так и скопированными в буфер обмена методом Range.Copy.
Параметры
Параметры | Описание |
---|---|
Destination | Необязательный параметр. Диапазон (ячейка), указывающий место вставки содержимого буфера обмена. Если этот параметр не указан, используется текущий выделенный объект. |
Link | Необязательный параметр. Булево значение, которое указывает, устанавливать ли ссылку на источник вставленных данных: True – устанавливать, False – не устанавливать (значение по умолчанию). |
В выражении с методом Worksheet.Paste можно указать только один из параметров: или Destination, или Link.
Для вставки из буфера обмена отдельных компонентов скопированных ячеек (значения, форматы, примечания и т.д.), а также для проведения транспонирования и вычислений, используйте метод Range.PasteSpecial (специальная вставка).
Примеры
Вырезание и вставка диапазона одной строкой (перемещение):
Вырезание ячеек в буфер обмена и вставка методом ActiveSheet.Paste:
Копирование и вставка диапазона одной строкой:
Копирование ячеек в буфер обмена и вставка методом ActiveSheet.Paste:
Копирование одной ячейки и вставка ее данных во все ячейки заданного диапазона:
43 комментария для “VBA Excel. Вырезание, копирование и вставка ячеек (диапазонов)”
Странно, что не рассмотрено копирование ячеек, которые Cells.
Например, следующая строка копирует ячейку A1 в B2
а эта делает тоже самое, но демонстрирует,
как можно добавить размер и смещение:
Здравствуйте!
Скажите, как можно копировать на Лист 1, а вставить на Лист 2 диапазон ячеек целиком, либо отсортированный по 1 признаку диапазон(например по какому-то определенному значению, скажем, числу «500» в одном столбце Листа 1)?
Привет, Максим!
Вот пример сортировки таблицы по значению 500 в первом столбце на «Лист6» и копирования диапазона с «Лист6» на «Лист4» :
Спасибо большое, только я, наверно, неправильно описал ситуацию.
Сперва из эталонной таблицы Лист 1 копируем весь список на существующий Лист4.
Затем, пропускаем шапку, и, начиная со строки7, уже на Лист4 ищем строку, у которой в столбце 5 стоит число 500.
Вырезаем эту строку и вставляем на позицию строки 7. т.е первая после шапки.
Ищем следующую строку — вырезаем, потом вставляем на позицию строки 7+1=8 и т.д.
В итоге оставим только те строки, у которых в столбце 5 стоит число «500», остальные удаляются строки.
(пробовал менять местами строки в предыдущем коде, ошибок нет, копирует, переходит на лист 4, но строки на нем не удаляет, циклы пошагово проходят, но ничего не изменяется.)
Источник
In this Article
- Rows & Columns – Paste vs. Insert
- Copy & Paste Over Existing Row / Column
- Copy & Insert Row / Column
- Copy Entire Row
- Cut and Paste Rows
- Copy Multiple Rows
- Copy Entire Column
- Cut and Paste Columns
- Copy Multiple Columns
- Copy Rows or Columns to Another Sheet
- Cut Rows or Columns to Another Sheet
This tutorial will teach you how to copy (or cut) entire Rows or Columns using VBA. We cover copying and pasting ranges of cells in another article.
First we will show you how to paste or insert copied rows/columns and discuss the differences. Then we will show you all of the different ways to references rows and columns when copying or cutting.
Rows & Columns – Paste vs. Insert
When pasting rows and columns you have two options: You can paste over the existing row (or column) or you can insert a new row (or column).
Let’s look at the difference…
Copy & Paste Over Existing Row / Column
This will copy row 1 and paste it into the existing row 5:
Range("1:1").Copy Range("5:5")
This will copy column C and paste it into column E:
Range("C:C").Copy Range("E:E")
Copy & Insert Row / Column
Instead you can insert the copied row or column and shift the existing rows or columns to make room.
This will copy row 1 and insert it into row 5, shifting the existing rows down:
Range("1:1").Copy
Range("5:5").Insert
This will copy column C and insert it into column E, shifting the existing columns to the right:
Range("C:C").Copy
Range("E:E").Insert
Copy Entire Row
Below we will show you several ways to copy row 1 and paste into row 5.
Range("1:1").Copy Range("5:5")
Range("A1").EntireRow.Copy Range("A5")
Rows(1).Copy Rows(5)
Cut and Paste Rows
Simply use Cut instead of Copy to cut and paste rows:
Rows(1).Cut Rows(5)
Copy Multiple Rows
Here are examples of copying multiple rows at once:
Range("5:7").Copy Range("10:13")
Range("A5:A7").EntireRow.Copy Range("A10:A13")
Rows("5:7").Copy Rows("10:13")
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
Copy Entire Column
You can copy entire columns similarily to copying entire rows:
Range("C:C").Copy Range("E:E")
Range("C1").EntireColumn.Copy Range("C1").EntireColumn
Columns(3).Copy Range(5)
Cut and Paste Columns
Simply use Cut instead of Copy to cut and paste columns:
Range("C:C").Cut Range("E:E")
Copy Multiple Columns
Here are examples of copying multiple columns at once:
Range("C:E").Copy Range("G:I")
Range("C1:E1").EntireColumn.Copy Range("G1:I1")
Columns("3:5").Copy Columns("7:9")
VBA Programming | Code Generator does work for you!
Copy Rows or Columns to Another Sheet
To copy to another sheet, simply use the Sheet Object:
Sheets("sheet1").Range("C:E").Copy Sheets("sheet2").Range("G:I")
Cut Rows or Columns to Another Sheet
You can use the exact same technique to cut and paste rows or columns to another sheet.
Sheets("sheet1").Range("C:E").Cut Sheets("sheet2").Range("G:I")
I have a named range like the following covering A2:D3
ITEM PRICE QTY SUBTOTAL
1 10 3 30
1 5 2 10
TOTAL: 40
I am to insert a new row using VBA into the range copying the formulas not values.
Any tips/links greatly appreciated.
0m3r
12.2k15 gold badges33 silver badges70 bronze badges
asked Apr 11, 2010 at 7:50
Samuel GoldenbaumSamuel Goldenbaum
18.1k17 gold badges66 silver badges102 bronze badges
1
This should do it:
Private Sub newRow(Optional line As Integer = -1)
Dim target As Range
Dim cell As Range
Dim rowNr As Integer
Set target = Range("A2:D3")
If line <> -1 Then
rowNr = line
Else
rowNr = target.Rows.Count
End If
target.Rows(rowNr + 1).Insert
target.Rows(rowNr).Copy target.Rows(rowNr + 1)
For Each cell In target.Rows(rowNr + 1).Cells
If Left(cell.Formula, 1) <> "=" Then cell.Clear
Next cell
End Sub
answered Apr 13, 2010 at 9:43
1
If you start recording a macro and actually do the task in hand, it will generate the code for you. Once finished, stop recording the macro and you’ll have the code needed which you can then amend.
answered Apr 11, 2010 at 7:52
Neil KnightNeil Knight
47.1k24 gold badges129 silver badges187 bronze badges
answered Apr 13, 2010 at 8:16
user183037user183037
2,5494 gold badges31 silver badges42 bronze badges
I needed to roll a solution that worked like the way a data connection query expands a result-range with optionally autofilling formulas off to the right. Perhaps two years late for the bounty, but I’m happy to share anyway!
Public Sub RangeExpand(rangeToExpand As Range, expandAfterLine As Integer, Optional linesToInsert As Integer = 1, Optional stuffOnTheRight As Boolean = False)
Debug.Assert rangeToExpand.Rows.Count > 1
Debug.Assert expandAfterLine < rangeToExpand.Rows.Count
Debug.Assert expandAfterLine > 0
If linesToInsert = 0 Then Exit Sub
Debug.Assert linesToInsert > 0
Do
rangeToExpand.EntireRow(expandAfterLine + 1).Insert
linesToInsert = linesToInsert - 1
Loop Until linesToInsert <= 0
If stuffOnTheRight Then
rangeToExpand.Item(expandAfterLine, rangeToExpand.Columns.Count + 1).Select
Range(Selection, Selection.End(xlToRight)).Select
Range(rangeToExpand.Item(expandAfterLine, 1), Selection).Select
Else
Range(rangeToExpand.Item(expandAfterLine, 1), rangeToExpand.Item(expandAfterLine, rangeToExpand.Columns.Count)).Select
End If
Selection.AutoFill Destination:=Range(rangeToExpand.Item(expandAfterLine, 1), rangeToExpand.Item(rangeToExpand.Rows.Count, Selection.Columns.Count))
End Sub
answered Jun 5, 2012 at 6:40
This Answer addresses the following 3 issues with the currently Accepted Answer from @marg originally posted Apr 13 ’10 at 9:43.
-
target.Rows(rowNr + 1).Insert
: 1.1. does not extend the Named Range by one Row (AFAIK the only way to do so implicitly via Insert Row (vs. explicitly modifying Range definition) and to do so after specified Row # is via Row #’s 1 to Count — 1) and 1.2) only shifts Columns in thetarget
Range down by one Row. In many (and probably most) cases, Columns to the right and/or left of thetarget
Range need to be shifted down as well. -
target.Rows(rowNr).Copy target.Rows(rowNr + 1)
does not copy
the Formats which are often if not usually desired also.
Private Sub InsertNewRowInRange( _
TargetRange As Range, _
Optional InsertAfterRowNumber As Integer = -1, _
Optional InsertEntireSheetRow As Boolean = True)
' -- InsertAfterRowNumber must be 1 to TargetRange.Rows.Count - 1 for TargetRange to be extended by one Row and for there to be
' -- Formats and Formulas to copy from (e.g. can't be 0). Default: If -1, defaults to TargetRange.Rows.Count.
' -- Recommend dummy spacer Row at the bottom of TargetRange which, btw, would also be necessary to manually extend a Range
' -- by one Row implicitly via Insert Row (vs. explicilty via changing Range definition).
If InsertAfterRowNumber = -1 Then
InsertAfterRowNumber = TargetRange.Rows.Count
End If
If InsertEntireSheetRow Then
TargetRange.Cells(InsertAfterRowNumber + 1, 1).Select
Selection.EntireRow.Insert
Else
TargetRange.Rows(InsertAfterRowNumber + 1).Insert
End If
TargetRange.Rows(InsertAfterRowNumber).Select
Selection.Copy
TargetRange.Rows(InsertAfterRowNumber + 1).Select
Selection.PasteSpecial _
Paste:=xlPasteFormats, _
Operation:=xlNone, _
SkipBlanks:=False, _
Transpose:=False
Selection.PasteSpecial _
Paste:=xlPasteFormulas, _
Operation:=xlNone, _
SkipBlanks:=False, _
Transpose:=False
Application.CutCopyMode = False
End Sub
answered Jul 22, 2017 at 1:41
TomTom
86211 silver badges13 bronze badges
4
Here’s another solution building on answer from @Tom. It does not use «Selection», and it’s possible to insert multiple rows.
' Appends one or more rows to a range.
' You can choose if you want to keep formulas and if you want to insert entire sheet rows.
Private Sub expand_range( _
target_range As Range, _
Optional num_rows As Integer = 1, _
Optional insert_entire_sheet_row As Boolean = False, _
Optional keep_formulas As Boolean = False _
)
Application.ScreenUpdating = False
On Error GoTo Cleanup
Dim original_cell As Range: Set original_cell = ActiveCell
Dim last_row As Range: Set last_row = target_range.Rows(target_range.Rows.Count)
' Insert new row(s) above the last row and copy contents from last row to the new one(s)
IIf(insert_entire_sheet_row, last_row.Cells(1).EntireRow, last_row) _
.Resize(num_rows).Insert Shift:=xlShiftDown, CopyOrigin:=xlFormatFromRightOrBelow
last_row.Copy
last_row.Offset(-num_rows).PasteSpecial
last_row.ClearContents
On Error Resume Next ' This will fail if there are no formulas and keep_formulas = True
If keep_formulas Then
With last_row.Offset(-num_rows).SpecialCells(xlCellTypeFormulas)
.Copy
.Offset(1).Resize(num_rows).PasteSpecial
End With
End If
On Error GoTo Cleanup
Cleanup:
On Error GoTo 0
Application.ScreenUpdating = True
Application.CutCopyMode = False
original_cell.Select
If Err Then Err.Raise Err.Number, , Err.Description
End Sub
answered Mar 1, 2018 at 13:59
In certain cases, you may need to automate the process of inserting a row (or several rows) in a worksheet. This is useful, for example, when you’re (i) manipulating or adding data entries, or (ii) formatting a worksheet that uses blank rows for organization purposes.
The information and examples in this VBA Tutorial should allow you to insert rows in a variety of circumstances.
This VBA Tutorial is accompanied by Excel workbooks containing the data and macros I use in the examples below. You can get immediate free access to these example workbooks by clicking the button below.
Use the following Table of Contents to navigate to the section you’re interested in.
Insert Rows in Excel
When working manually with Excel, you can insert rows in the following 2 steps:
- Select the row or rows above which to insert the row or rows.
- Do one of the following:
- Right-click and select Insert.
- Go to Home > Insert > Insert Sheet Rows.
- Use the “Ctrl + Shift + +” keyboard shortcut.
You can use the VBA constructs and structures I describe below to automate this process to achieve a variety of results.
Excel VBA Constructs to Insert Rows
Insert Rows with the Range.Insert Method
Purpose of Range.Insert
Use the Range.Insert method to insert a cell range into a worksheet. The 2 main characteristics of the Range.Insert method are the following:
- Range.Insert can insert a single cell or a cell range. For purposes of this VBA Tutorial, you’re interested in inserting entire rows.
- To make space for the newly-inserted cells, Range.Insert shifts other cells away.
Syntax of Range.Insert
expression.Insert(Shift, CopyOrigin)
“expression” is a Range object. Therefore, I simplify as follows:
Range.Insert(Shift, CopyOrigin)
Parameters of Range.Insert
- Parameter: Shift.
- Description: Specifies the direction in which cells are shifted away to make space for the newly-inserted row.
- Optional/Required: Optional.
- Data type: Variant.
- Values: Use a constant from the xlInsertShiftDirection Enumeration:
- xlShiftDown or -4121: Shifts cells down.
- xlShiftToRight or -4161: Shifts cells to the right.
- Default: Excel decides based on the range’s shape.
- Usage notes: When you insert a row: (i) use xlShiftDown or -4121, or (ii) omit parameter and rely on the default behavior.
- Parameter: CopyOrigin.
- Description: Specifies from where (the origin) is the format for the cells in the newly inserted row copied.
- Optional/Required: Optional.
- Data type: Variant.
- Values: A constant from the xlInsertFormatOrigin Enumeration:
- xlFormatFromLeftOrAbove or 0: Newly-inserted cells take formatting from cells above or to the left.
- xlFormatFromRightOrBelow or 1: Newly-inserted cells take formatting from cells below or to the right.
- Default: xlFormatFromLeftOrAbove or 0. Newly-inserted cells take the formatting from cells above or to the left.
How to Use Range.Insert to Insert Rows
Use the Range.Insert method to insert a row into a worksheet. Use a statement with the following structure:
Range.Insert Shift:=xlShiftDown CopyOrigin:=xlInsertFormatOriginConstant
For these purposes:
- Range: Range object representing an entire row. Use the Worksheet.Rows or Range.EntireRow properties to return a Range object that represents the entire row. Please refer to the sections about the Rows and EntireRow properties below.
- xlInsertFormatOriginConstant: xlFormatFromLeftOrAbove or xlFormatFromRightOrBelow. xlFormatFromLeftOrAbove is the default value. Therefore, when inserting rows with formatting from row above, you can usually omit the CopyOrigin parameter.
You can usually omit the Shift parameter. By default, VBA decides how to shift the cells based on the range’s shape. When inserting a row, this usually results in Excel shifting the cells down.
Specify Rows with the Worksheet.Rows Property
Purpose of Worksheet.Rows
Use the Worksheet.Rows property to return a Range object representing all the rows within the worksheet the property works with.
Worksheet.Rows is read-only.
Syntax of Worksheet.Rows
expression.Rows
“expression” is a Worksheet object. Therefore, I simplify as follows:
Worksheet.Rows
How to Use Worksheet.Rows to Insert Rows
Use the Worksheet.Rows property to specify the row or rows above which new rows are inserted.
To insert a row, use a statement with the following structure:
Worksheets.Rows(row#).Insert
“row#” is the number of the row above which the row is inserted.
To insert multiple rows, use a statement with the following structure:
Worksheet.Rows("firstRow#:lastRow#").Insert
“firstRow#” is the row above which the rows are inserted. The number of rows VBA inserts is calculated as follows:
lastRow# - firstRow# + 1
Specify the Active Cell with the Application.ActiveCell Property
Purpose of Application.ActiveCell
Use the Application.ActiveCell property to return a Range object representing the active cell.
Application.ActiveCell is read-only.
Syntax of Application.ActiveCell
expression.ActiveCell
“expression” is the Application object. Therefore, I simplify as follows:
Application.ActiveCell
How to Use Application.ActiveCell To Insert Rows
When you insert a row, use the Application.ActiveCell property to return the active cell. This allows you to use the active cell as reference for the row insertion operation.
Use the Range.Offset property to return a Range object a specific number of rows above or below the active cell. Use the Range.EntireRow property to return a Range object representing the entire row or rows above which to insert the new row. Please refer to the sections about the Offset and EntireRow properties below.
To insert a row above the active cell, use the following statement:
ActiveCell.EntireRow.Insert Shift:=xlShiftDown
To insert a row a specific number of rows above or below the active cell, use a statement with the following structure:
ActiveCell.Offset(RowOffset).EntireRow.Insert Shift:=xlShiftDown
Specify a Cell Range with the Worksheet.Range Property
Purpose of Worksheet.Range
Use the Worksheet.Range property to return a Range object representing a single cell or a cell range.
Syntax of Worksheet.Range
expression.Range(Cell1, Cell2)
“expression” is a Worksheet object. Therefore, I simplify as follows:
Worksheet.Range(Cell1, Cell2)
Parameters of Worksheet.Range
- Parameter: Cell1.
- Description:
- If you use Cell1 alone (omit Cell2), Cell1 specifies the cell range.
- If you use Cell1 and Cell2, Cell1 specifies the cell in the upper-left corner of the cell range.
- Required/Optional: Required.
- Data type: Variant.
- Values:
- If you use Cell1 alone (omit Cell2): (i) range address as an A1-style reference in language of macro, or (ii) range name.
- If you use Cell1 and Cell2: (i) Range object, (ii) range address, or (iii) range name.
- Description:
- Parameter: Cell2.
- Description: Cell in the lower-right corner of the cell range.
- Required/Optional: Optional.
- Data type: Variant.
- Values: (i) Range object, (ii) range address, or (iii) range name.
How to Use Worksheet.Range to Insert Rows
When you insert a row, use the Worksheet.Range property to return a cell or cell range. This allows you to use a specific cell or cell range as reference for the row insertion operation.
Use the Range.Offset property to return a Range object a specific number of rows above or below the cell or cell range. Use the Range.EntireRow property to return a Range object representing the entire row or rows above which to insert the new row or rows. Please refer to the sections about the Offset and EntireRow properties below.
To insert rows above the cell range specified by Worksheet.Range, use a statement with the following structure:
Worksheet.Range(Cell1, Cell2).EntireRow.Insert Shift:=xlShiftDown
To insert rows a specific number of rows above or below the cell range specified by Worksheet.Range use a statement with the following structure:
Worksheet.Range(Cell1, Cell2).Offset(RowOffset).EntireRow.Insert Shift:=xlShiftDown
If the cell range represented by the Worksheet.Range property spans more than 1 row, the Insert method inserts several rows. The number of rows inserted is calculated as follows:
lastRow# - firstRow# + 1
Please refer to the section about the Worksheet.Rows property above for further information about this calculation.
Specify a Cell with the Worksheet.Cells and Range.Item Properties
Purpose of Worksheet.Cells and Range.Item
Use the Worksheet.Cells property to return a Range object representing all the cells within a worksheet.
Once your macro has all the cells within the worksheet, use the Range.Item property to return a Range object representing one of those cells.
Syntax of Worksheet.Cells and Range.Item
Worksheet.Cells
expression.Cells
“expression” is a Worksheet object. Therefore, I simplify as follows:
Worksheet.Cells
Range.Item
expression.Item(RowIndex, ColumnIndex)
“expression” is a Range object. Therefore, I simplify as follows:
Range.Item(RowIndex, ColumnIndex)
Worksheet.Cells and Range.Item Together
Considering the above:
Worksheet.Cells.Item(RowIndex, ColumnIndex)
However, Item is the default property of the Range object. Therefore, you can generally omit the Item keyword before specifying the RowIndex and ColumnIndex arguments. I simplify as follows:
Worksheet.Cells(RowIndex, ColumnIndex)
Parameters of Worksheet.Cells and Range.Item
- Parameter: RowIndex.
- Description:
- If you use RowIndex alone (omit ColumnIndex), RowIndex specifies the index of the cell you work with. Cells are numbered from left-to-right and top-to-bottom.
- If you use RowIndex and ColumnIndex, RowIndex specifies the row number of the cell you work with.
- Required/Optional: Required.
- Data type: Variant.
- Values: You usually specify RowIndex as a value.
- Description:
- Parameter: ColumnIndex.
- Description: Column number or letter of the cell you work with.
- Required/Optional: Optional.
- Data type: Variant.
- Values: You usually specify ColumnIndex as a value (column number) or letter within quotations (“”).
How to use Worksheet.Cells and Range.Item to Insert Rows
When you insert a row, use the Worksheet.Cells and Range.Item properties to return a cell. This allows you to use a specific cell as reference for the row insertion operation.
Use the Range.Offset property to return a Range object a specific number of rows above or below the cell. Use the Range.EntireRow property to return a Range object representing the entire row above which to insert the row. Please refer to the sections about the Offset and EntireRow properties below.
To insert a row above the cell specified by Worksheet.Cells, use a statement with the following structure:
Worksheet.Cells(RowIndex, ColumnIndex).EntireRow.Insert Shift:=xlShiftDown
To insert a row a specific number of rows above or below the cell specified by Worksheet.Cells, use a statement with the following structure:
Worksheet.Cells(RowIndex, ColumnIndex).Offset(RowOffset).EntireRow.Insert Shift:=xlShiftDown
Specify a Cell Range a Specific Number of Rows Below or Above a Cell or Cell Range with the Range.Offset Property
Purpose of Range.Offset
Use the Range.Offset property to return a Range object representing a cell range located a number of rows or columns away from the range the property works with.
Syntax of Range.Offset
expression.Offset(RowOffset, ColumnOffset)
“expression” is a Range object. Therefore, I simplify as follows:
Range.Offset(RowOffset, ColumnOffset)
Parameters of Range.Offset
- Parameter: RowOffset.
- Description: Number of rows by which cell or cell range is offset.
- Required/Optional: Optional.
- Data type: Variant.
- Values:
- Positive number: Moves down the worksheet.
- Negative number: Moves up the worksheet.
- 0: Stays on the same row.
- Default: 0. Stays on the same row.
- Parameter: ColumnOffset.
- Description: Number of columns by which cell or cell range is offset.
- Required/Optional: Optional.
- Data type: Variant.
- Values:
- Positive number: Moves towards the right of the worksheet.
- Negative number: Moves towards the left of the worksheet.
- 0: Stays on the same column.
- Default: 0. Stays on the same column.
- Usage notes: When you insert a row, you can usually omit the ColumnOffset parameter. You’re generally interested in moving a number of rows (not columns) above or below.
How to Use Range.Offset to Insert Rows
When you insert a row, use the Range.Offset property to specify a cell or cell range located a specific number of rows below above another cell or cell range. This allows you to use this new cell or cell range as reference for the row insertion operation.
Use properties such as Application.ActiveCell, Worksheet.Range and Worksheet.Cells to specify the base range the Offset property works with. Please refer to the sections about the ActiveCell, Range and Cells properties above.
Specify Entire Row with the Range.EntireRow Property
Purpose of Range.EntireRow
Use the Range.EntireRow property to return a Range object representing the entire row or rows containing the cell range the property works with.
Range.EntireRow is read-only.
Syntax of Range.EntireRow
expression.EntireRow
“expression” is a Range object. Therefore, I simplify as follows:
Range.EntireRow
How to Use Range.EntireRow to Insert Rows
When you insert a row, use the Range.EntireRow property to return the entire row or rows above which the new row or rows are inserted.
Use properties such as Application.ActiveCell, Worksheet.Range and Worksheet.Cells to specify the range the EntireRow property works with. Please refer to the sections about the ActiveCell, Range and Cells properties above.
Clear Row Formatting with the Range.ClearFormats Method
Purpose of Range.ClearFormats
Use the Range.ClearFormats method to clear the formatting of a cell range.
Syntax of Range.ClearFormats
expression.ClearFormats
“expression” is a Range object. Therefore, I simplify as follows:
Range.ClearFormats
How to Use Range.ClearFormats to Insert Rows
The format of the newly-inserted row is specified by the CopyOrigin parameter of the Range.Insert method. Please refer to the description of Range.Insert and CopyOrigin above.
When you insert a row, use the Range.ClearFormats method to clear the formatting of the newly-inserted rows. Use a statement with the following structure after the statement that inserts the new row (whose formatting you want to clear):
Range.ClearFormats
“Range” is a Range object representing the newly-inserted row.
Use the Worksheet.Rows or Range.EntireRow properties to return a Range object that represents the newly-inserted row. Please refer to the sections about the Rows and EntireRow properties above.
Copy Rows with the Range.Copy Method
Purpose of Range.Copy
Use the Range.Copy method to copy a cell range to another cell range or the Clipboard.
Syntax of Range.Copy
expression.Copy(Destination)
“expression” is a Range object. Therefore, I simplify as follows:
Range.Copy(Destination)
Parameters of Range.Copy
- Parameter: Destination.
- Description: Specifies the destination cell range to which the copied cell range is copied.
- Required/Optional: Optional parameter.
- Data type: Variant.
- Values: You usually specify Destination as a Range object.
- Default: Cell range is copied to the Clipboard.
- Usage notes: When you insert a copied row, omit the Destination parameter to copy the row to the Clipboard.
How to Use Range.Copy to Insert Rows
Use the Range.Copy method to copy a row which you later insert.
Use a statement with the following structure before the statement that inserts the row:
Range.Copy
“Range” is a Range object representing an entire row.
Use the Worksheet.Rows or Range.EntireRow properties to return a Range object that represents a row. Please refer to the sections about the Rows and EntireRow properties above.
Related VBA and Macro Tutorials
- General VBA constructs and structures:
- Introduction to Excel VBA constructs and structures.
- The Excel VBA Object Model.
- How to declare variables in Excel VBA.
- Excel VBA data types.
- Practical VBA applications and macro examples:
- How to copy and paste with Excel VBA.
You can find additional VBA and Macro Tutorials in the Archives.
Example Workbooks
This VBA Tutorial is accompanied by Excel workbooks containing the data and macros I explain below. If you want to follow and practice, you can get immediate free access to these example workbooks by clicking the button below.
Each worksheet within the workbook contains a single data range. Most of the entries simply state “Data”.
Example #1: Excel VBA Insert Row
VBA Code to Insert Row
The following macro inserts a row below row 5 of the worksheet named “Insert row”.
Sub insertRow() 'Source: powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-insert-row/ Worksheets("Insert row").Rows(6).Insert Shift:=xlShiftDown End Sub
Process Followed by Macro
VBA Statement Explanation
Worksheets(“Insert row”).Rows(6).Insert Shift:=xlShiftDown
- Item: Worksheets(“Insert row”).
- VBA construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the “Insert row” worksheet.
- Item: Rows(6).
- VBA construct: Worksheets.Rows property.
- Description: Returns a Range object representing row 6 of the worksheet returned by item #1 above.
- Item: Insert.
- VBA construct: Range.Insert method.
- Description: Inserts a new row above the row returned by item #2 above.
- Item: Shift:=xlShiftDown.
- VBA construct: Shift parameter of Range.Insert method.
- Description:
- Shifts rows down (xlShiftDown) to make space for the row inserted by item #3 above.
- You can usually omit this parameter. By default, VBA decides how to shift the cells based on the range’s shape. When inserting a row, this usually results in Excel shifting the cells down.
Effects of Executing the Macro
The following GIF illustrates the results of executing this macro. As expected, VBA inserts a row below row 5 of the worksheet.
Example #2: Excel VBA Insert Multiple Rows
VBA Code to Insert Multiple Rows
The following macro inserts 5 rows below row 10 of the worksheet named “Insert row”.
Sub insertMultipleRows() 'Source: powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-insert-row/ Worksheets("Insert row").Rows("11:15").Insert Shift:=xlShiftDown End Sub
Process Followed by Macro
VBA Statement Explanation
Worksheets(“Insert row”).Rows(“11:15”).Insert Shift:=xlShiftDown
- Item: Worksheets(“Insert row”).
- VBA construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the “Insert row” worksheet.
- Item: Rows(“11:15”).
- VBA construct: Worksheet.Rows property.
- Description: Returns a Range object representing rows 11 to 15 of the worksheet returned by item #1 above.
- Item: Insert.
- VBA construct: Range.Insert method.
- Description:
- Inserts new rows above the rows returned by item #2 above.
- The number of inserted rows is equal to the number of rows returned by item #2 above. This is calculated as follows:
lastRow# - firstRow# + 1
In this example:
15 - 11 + 1 = 5
- Item: Shift:=xlShiftDown.
- VBA construct: Shift parameter of Range.Insert method.
- Description:
- Shifts rows down (xlShiftDown) to make space for the rows inserted by item #3 above.
- You can usually omit this parameter. By default, VBA decides how to shift the cells based on the range’s shape. When inserting a row, this usually results in Excel shifting the cells down.
Effects of Executing the Macro
The following GIF illustrates the results of executing this macro. As expected, VBA inserts 5 rows below row 10 of the worksheet.
Example #3: Excel VBA Insert Row with Same Format as Row Above
VBA Code to Insert Row with Same Format as Row Above
The following macro (i) inserts a row below row 20, and (ii) applies the formatting of row 20 to the newly-inserted row.
Sub insertRowFormatFromAbove() 'Source: powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-insert-row/ Worksheets("Insert row").Rows(21).Insert Shift:=xlShiftDown, CopyOrigin:=xlFormatFromLeftOrAbove End Sub
Process Followed by Macro
VBA Statement Explanation
Worksheets(“Insert row”).Rows(21).Insert Shift:=xlShiftDown, CopyOrigin:=xlFormatFromLeftOrAbove
- Item: Worksheets(“Insert row”).
- VBA construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the “Insert row” worksheet.
- Item: Rows(21).
- VBA construct: Worksheet.Rows property.
- Description: Returns a Range object representing row 21 of the worksheet returned by item #1 above.
- Item: Insert.
- VBA construct: Range.Insert method.
- Description: Inserts a new row above the row returned by item #2 above.
- Item: Shift:=xlShiftDown.
- VBA construct: Shift parameter of Range.Insert method.
- Description:
- Shifts rows down (xlShiftDown) to make space for the row inserted by item #3 above.
- You can usually omit this parameter. By default, VBA decides how to shift the cells based on the range’s shape. When inserting a row, this usually results in Excel shifting the cells down.
- Item: CopyOrigin:=xlFormatFromLeftOrAbove.
- VBA construct: CopyOrigin parameter of Range.Insert method.
- Description:
- Sets formatting of row inserted by item #3 above to be equal to that of row above (xlFormatFromLeftOrAbove).
- You can usually omit this parameter. xlFormatFromLeftOrAbove (or 0) is the default value of CopyOrigin.
Effects of Executing the Macro
The following GIF illustrates the results of executing this macro. As expected, VBA (i) inserts a row below row 20, and (ii) applies the formatting of row 20 to the newly-inserted row.
Example #4: Excel VBA Insert Row with Same Format as Row Below
VBA Code to Insert Row with Same Format as Row Below
The following macro (i) inserts a row below row 25, and (ii) applies the formatting of the row below to the newly-inserted row.
Sub insertRowFormatFromBelow() 'Source: powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-insert-row/ Worksheets("Insert row").Rows(26).Insert Shift:=xlShiftDown, CopyOrigin:=xlFormatFromRightOrBelow End Sub
Process Followed by Macro
VBA Statement Explanation
Worksheets(“Insert row”).Rows(26).Insert Shift:=xlShiftDown, CopyOrigin:=xlFormatFromRightOrBelow
- Item: Worksheets(“Insert row”).
- VBA construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the “Insert row” worksheet.
- Item: Rows(26).
- VBA construct: Worksheet.Rows property.
- Description: Returns a Range object representing row 26 of the worksheet returned by item #1 above.
- Item: Insert.
- VBA construct: Range.Insert method.
- Description: Inserts a new row above the row returned by item #2 above.
- Item: Shift:=xlShiftDown.
- VBA construct: Shift parameter of Range.Insert method.
- Description:
- Shifts rows down (xlShiftDown) to make space for the row inserted by item #3 above.
- You can usually omit this parameter. By default, VBA decides how to shift the cells based on the range’s shape. When inserting a row, this usually results in Excel shifting the cells down.
- Item: CopyOrigin:=xlFormatFromRightOrBelow.
- VBA construct: CopyOrigin parameter of Range.Insert method.
- Description: Sets formatting of row inserted by item #3 above to be equal to that of row below (xlFormatFromRightOrBelow).
Effects of Executing the Macro
The following GIF illustrates the results of executing this macro. As expected, VBA (i) inserts a row below row 25, and (ii) applies the formatting of the row below to the newly-inserted row.
Example #5: Excel VBA Insert Row without Formatting
VBA Code to Insert Row without Formatting
The following macro inserts a row below row 30 without applying the formatting from the rows above or below the newly- inserted row.
Sub insertRowWithoutFormat() 'Source: powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-insert-row/ Dim myNewRowNumber As Long myNewRowNumber = 31 With Worksheets("Insert row") .Rows(myNewRowNumber).Insert Shift:=xlShiftDown .Rows(myNewRowNumber).ClearFormats End With End Sub
Process Followed by Macro
VBA Statement Explanation
Lines #4 and #5: Dim myNewRowNumber As Long | myNewRowNumber = 31
- Item: Dim myNewRowNumber As Long.
- VBA construct: Dim statement.
- Description:
- Declares a new variable (myNewRowNumber) as of the Long data type.
- myNewRowNumber represents the number of the newly inserted row.
- Item: myNewRowNumber = 31.
- VBA construct: Assignment statement.
- Description: Assigns the value 31 to myNewRowNumber
Lines #6 and #9: With Worksheets(“Insert row”) | End With
- Item: With | End With.
- VBA construct: With… End With statement.
- Description: Statements within the With… End With statement (lines #7 and #8 below) are executed on the worksheet returned by item #2 below.
- Item: Worksheets(“Insert row”).
- VBA construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the “Insert row” worksheet.
Line #7: .Rows(myNewRowNumber).Insert Shift:=xlShiftDown
- Item: Rows(myNewRowNumber).
- VBA construct: Worksheet.Rows property.
- Description:
- Returns a Range object representing a row (whose number is represented by myNewRowNumber) of the worksheet in the opening statement of the With… End With statement (line #6 above).
- In this example, myNewRowNumber equals 31. Therefore, Worksheet.Rows returns row 31 prior to the insertion of the new row. This is a different row from that returned by Worksheet.Rows in line #8 below.
- This line #7 returns a row prior to the row insertion. This line is that above which the new row is inserted.
- Line #8 below returns a row after the row insertion. This line is the newly-inserted row.
- Item: Insert.
- VBA construct: Range.Insert method.
- Description: Inserts a new row above the row returned by item #1 above.
- Item: Shift:=xlShiftDown.
- VBA construct: Shift parameter of Range.Insert method.
- Description:
- Shifts rows down (xlShiftDown) to make space for the row inserted by item #2 above.
- You can usually omit this parameter. By default, VBA decides how to shift the cells based on the range’s shape. When inserting a row, this usually results in Excel shifting the cells down.
Line #8: .Rows(myNewRowNumber).ClearFormats
- Item: Rows(myNewRowNumber).
- VBA construct: Worksheet.Rows property.
- Description:
- Returns a Range object representing a row (whose number is represented by myNewRowNumber) of the worksheet in the opening statement of the With… End With statement (line #6 above).
- In this example, myNewRowNumber equals 31. Therefore, Worksheet.Rows returns row 31 after the insertion of the new row. This is a different row from that returned by Worksheet.Rows in line #7 above.
- This line #8 returns a row after the row insertion. This line is the newly-inserted row.
- Line #7 above returns a row prior to the row insertion. This line is that below the newly-inserted row.
- Item: ClearFormats.
- VBA construct: Range.ClearFormats method.
- Description: Clears the formatting of the row returned by item #1 above.
Effects of Executing the Macro
The following GIF illustrates the results of executing this macro. As expected, VBA inserts a row below row 30 without applying the formatting from the rows above or below the newly- inserted row.
Example #6: Excel VBA Insert Row Below Active Cell
VBA Code to Insert Row Below Active Cell
The following macro inserts a row below the active cell.
Sub insertRowBelowActiveCell() 'Source: powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-insert-row/ ActiveCell.Offset(1).EntireRow.Insert Shift:=xlShiftDown End Sub
Process Followed by Macro
VBA Statement Explanation
ActiveCell.Offset(1).EntireRow.Insert Shift:=xlShiftDown
- Item: ActiveCell.
- VBA construct: Application.ActiveCell property.
- Description: Returns a Range object representing the active cell.
- Item: Offset(1).
- VBA construct: Range.Offset property.
- Description:
- Returns a Range object representing the cell range 1 row below the cell returned by item #1 above.
- In this example, Range.Offset returns the cell immediately below the active cell.
- Item: EntireRow:
- VBA construct: Range.EntireRow property.
- Description: Returns a Range object representing the entire row containing the cell range returned by item #2 above.
- Item: Insert.
- VBA construct: Range.Insert method.
- Description: Inserts a new row above the row returned by item #3 above.
- Item: Shift:=xlShiftDown.
- VBA construct: Shift parameter of Range.Insert method.
- Description:
- Shifts rows down (xlShiftDown) to make space for the row inserted by item #4 above.
- You can usually omit this parameter. By default, VBA decides how to shift the cells based on the range’s shape. When inserting a row, this usually results in Excel shifting the cells down.
Effects of Executing the Macro
The following GIF illustrates the results of executing this macro. When I execute the macro, the active cell is B35. As expected, inserts a row below the active cell.
Example #7: Excel VBA Insert Copied Row
VBA Code to Insert Copied Row
The following macro (i) copies row 45, and (ii) inserts the copied row below row 40.
Sub insertCopiedRow() 'Source: powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-insert-row/ With Worksheets("Insert row") .Rows(45).Copy .Rows(41).Insert Shift:=xlShiftDown End With Application.CutCopyMode = False End Sub
Process Followed by Macro
VBA Statement Explanation
Lines #4 and #7: With Worksheets(“Insert row”) | End With
- Item: With | End With.
- VBA construct: With… End With statement.
- Description: Statements within the With… End With statement (lines #5 and #6 below) are executed on the worksheet returned by item #2 below.
- Item: Worksheets(“Insert row”).
- VBA construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the “Insert row” worksheet.
Line #5: .Rows(45).Copy
- Item: Rows(45).
- VBA construct: Worksheet.Rows property.
- Description: Returns a Range object representing row 45 of the worksheet in the opening statement of the With… End With statement (line #4 above).
- Item: Copy.
- VBA construct: Range.Copy method.
- Description: Copies the row returned by item #1 above to the Clipboard.
Line #6: .Rows(41).Insert Shift:=xlShiftDown
- Item: Rows(41).
- VBA construct: Worksheet.Rows property.
- Description: Returns a Range object representing row 41 of the worksheet in the opening statement of the With… End With statement (line #4 above).
- Item: Insert.
- VBA construct: Range.Insert method.
- Description:
- Inserts a new row above the row returned by item #1 above.
- The newly-inserted row isn’t blank. VBA inserts the row copied by line #5 above.
- Item: Shift:=xlShiftDown.
- VBA construct: Shift parameter of Range.Insert method.
- Description:
- Shifts rows down (xlShiftDown) to make space for the row inserted by item #2 above.
- You can usually omit this parameter. By default, VBA decides how to shift the cells based on the range’s shape. When inserting a row, this usually results in Excel shifting the cells down.
Line #8: Application.CutCopyMode = False
- Item: Application.CutCopyMode = False.
- VBA construct: Application.CutCopyMode property.
- Description: Cancels (False) the Cut or Copy mode and removes the moving border that accompanies this mode.
Effects of Executing the Macro
The following GIF illustrates the results of executing this macro. As expected, VBA (i) copies row 45, and (ii) inserts the copied row below row 40.
Example #8: Excel VBA Insert Blank Rows Between Rows in a Data Range
VBA Code to Insert Blank Rows Between Rows in a Data Range
The following macro inserts blank rows within the specified data range. This results in all rows within the data range being separated by a blank row.
Sub insertBlankRowsBetweenRows() 'Source: powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-insert-row/ Dim myFirstRow As Long Dim myLastRow As Long Dim myWorksheet As Worksheet Dim iCounter As Long myFirstRow = 5 Set myWorksheet = Worksheets("Insert blank rows") myLastRow = myWorksheet.Cells.Find( _ What:="*", _ LookIn:=xlFormulas, _ LookAt:=xlPart, _ SearchOrder:=xlByRows, _ SearchDirection:=xlPrevious).Row For iCounter = myLastRow To (myFirstRow + 1) Step -1 myWorksheet.Rows(iCounter).Insert Shift:=xlShiftDown Next iCounter End Sub
Process Followed by Macro
VBA Statement Explanation
Lines #4 through #9: Dim myFirstRow As Long | Dim myLastRow As Long | Dim myWorksheet As Worksheet | Dim iCounter As Long | myFirstRow = 5 | Set myWorksheet = Worksheets(“Insert blank rows”)
- Item: Dim myFirstRow As Long.
- VBA construct: Dim statement.
- Description:
- Declares a new variable (myFirstRow) as of the Long data type.
- myFirstRow represents the number of the first row with data in the data range you work with.
- Item: Dim myLastRow As Long.
- VBA construct: Dim statement.
- Description:
- Declares a new variable (myLastRow) as of the Long data type.
- myLastRow represents the number of the last row with data in the data range you work with.
- Item: Dim myWorksheet As Worksheet.
- VBA construct: Dim statement.
- Description:
- Declares a new object variable (myWorksheet) to reference a Worksheet object.
- myWorksheet represents the worksheet you work with.
- Item: Dim iCounter As Long.
- VBA construct: Dim statement.
- Description:
- Declares a new variable (iCounter) as of the Long data type.
- iCounter represents a loop counter.
- Item: myFirstRow = 5.
- VBA construct: Assignment statement.
- Description: Assigns the value 5 to myFirstRow.
- Item: Set myWorksheet = Worksheets(“Insert blank rows”).
- VBA constructs:
- Set statement.
- Workbooks.Worksheets property.
- Description: Assigns the Worksheet object representing the “Insert blank rows” worksheet to myWorksheet.
- VBA constructs:
Lines #10 through #15: myLastRow = myWorksheet.Cells.Find( What:=”*”, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
- Item: myLastRow =.
- VBA construct: Assignment statement.
- Description: Assigns the value returned by items #2 through #9 below to myLastRow.
- Item: myWorksheet.Cells.
- VBA construct: Worksheet.Cells property.
- Description: Returns a Range object representing all cells on myWorksheet.
- Item: Find.
- VBA construct: Range.Find method.
- Description:
- Finds information in the cell range returned by item #2 above and returns a Range object representing the first cell where the information is found.
- In this example, the Range object Range.Find returns represents the last cell with data in last row with data in myWorksheet.
- Item: What:=”*”.
- VBA construct: What parameter of Range.Find method.
- Description: Specifies the data Range.Find searches for. The asterisk (*) is a wildcard and, therefore, Range.Find searches for any character sequence.
- Item: LookIn:=xlFormulas.
- VBA construct: LookIn parameter of Range.Find method.
- Description: Specifies that Range.Find looks in formulas (xlFormulas).
- Item: LookAt:=xlPart.
- VBA construct: LookAt parameter of Range.Find method.
- Description: Specifies that Range.Find looks at (and matches) a part (xlPart) of the search data.
- Item: SearchOrder:=xlByRows.
- VBA construct: SearchOrder parameter of Range.Find method.
- Description: Specifies that Range.Find searches by rows (xlByRows).
- Item: SearchDirection:=xlPrevious.
- VBA construct: SearchDirection parameter of Range.Find method.
- Description: Specifies that Range.Find searches for the previous match (xlPrevious).
- Item: Row.
- VBA construct: Range.Row property.
- Description:
- Returns the row number of the Range object returned by item #3 above.
- In this example, the number returned by Range.Row corresponds to the last row with data in myWorksheet.
Lines #16 and #18: For iCounter = myLastRow To (myFirstRow + 1) Step -1 | Next iCounter
- Item: For | Next iCounter.
- VBA construct: For… Next statement.
- Description:
- Repeats the statement inside the For… Next loop (line #17 below) a specific number of times.
- In this example:
- The macro starts on the last row of the data range as specified by item #2 below.
- Every iteration, the loop counter decreases by 1, as specified by item #4 below. Therefore, the macro moves to the previous row.
- The macro exits the loop after working with the second row in the data range (myFirstRow + 1), as specified by item #3 below.
- Item: iCounter = myLastRow.
- VBA construct: Counter and Start of For… Next statement.
- Description: Specifies myLastRow as the initial value of the loop counter (iCounter).
- Item: To (myFirstRow + 1).
- VBA construct: End of For… Next statement.
- Description: Specifies the value represented by myFirstRow plus 1 (myFirstRow + 1) as the final value of the loop counter.
- Item: Step -1.
- VBA construct: Step of For… Next statement.
- Description: Specifies that the loop counter (iCounter) decreases by 1 (-1) every loop iteration.
Line #17: myWorksheet.Rows(iCounter).Insert Shift:=xlShiftDown
- Item: myWorksheet.Rows(iCounter).
- VBA construct: Worksheet.Rows property.
- Description:
- Returns a Range object representing the row (whose number is represented by iCounter) of myWorksheet.
- Worksheet.Rows returns the row through which the macro is currently looping.
- Item: Insert.
- VBA construct: Range.Insert method.
- Description:
- Inserts a new row above the row returned by item #1 above.
- The macro loops through each line in the data range (excluding the first) as specified by lines #16 and #18 above. Therefore, Range.Insert inserts a row between all rows with data.
- Item: Shift:=xlShiftDown.
- VBA construct: Shift parameter of Range.Insert method.
- Description:
- Shifts rows down (xlShiftDown) to make space for the row inserted by item #2 above.
- You can usually omit this parameter. By default, VBA decides how to shift the cells based on the range’s shape. When inserting a row, this usually results in Excel shifting the cells down.
Effects of Executing the Macro
The following GIF illustrates the results of executing this macro. As expected, VBA inserts blank rows within the specified data range. This results in all rows within the data range being separated by a blank row.
Example #9: Excel VBA Insert a Number of Rows Every Number of Rows in a Data Range
VBA Code to Insert a Number of Rows Every Number of Rows in a Data Range
The following macro inserts 2 rows every 3 rows within the specified data range.
Sub insertMRowsEveryNRows() 'Source: powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-insert-row/ Dim myFirstRow As Long Dim myLastRow As Long Dim myNRows As Long Dim myRowsToInsert As Long Dim myWorksheet As Worksheet Dim iCounter As Long myFirstRow = 5 myNRows = 3 myRowsToInsert = 2 Set myWorksheet = Worksheets("Insert M rows every N rows") myLastRow = myWorksheet.Cells.Find( _ What:="*", _ LookIn:=xlFormulas, _ LookAt:=xlPart, _ SearchOrder:=xlByRows, _ SearchDirection:=xlPrevious).Row For iCounter = myLastRow To (myFirstRow + myNRows) Step -1 If (iCounter - myFirstRow) Mod myNRows = 0 Then myWorksheet.Rows(iCounter & ":" & iCounter + myRowsToInsert - 1).Insert Shift:=xlShiftDown Next iCounter End Sub
Process Followed by Macro
VBA Statement Explanation
Lines #4 through 13: Dim myFirstRow As Long | Dim myLastRow As Long | Dim myNRows As Long | Dim myRowsToInsert As Long | Dim myWorksheet As Worksheet | Dim iCounter As Long | myFirstRow = 5 | myNRows = 3 | myRowsToInsert = 2 | Set myWorksheet = Worksheets(“Insert M rows every N rows”)
- Item: Dim myFirstRow As Long.
- VBA construct: Dim statement.
- Description:
- Declares a new variable (myFirstRow) as of the Long data type.
- myFirstRow represents the number of the first row with data in the data range you work with.
- Item: Dim myLastRow As Long.
- VBA construct: Dim statement.
- Description:
- Declares a new variable (myLastRow) as of the Long data type.
- myLastRow represents the number of the last row with data in the data range you work with.
- Item: Dim myNRows As Long.
- VBA construct: Dim statement.
- Description:
- Declares a new variable (myNRows) as of the Long data type.
- myNRows represents the number of rows per block. The macro doesn’t insert rows between these rows.
- Item: Dim myRowsToInsert As Long.
- VBA construct: Dim statement.
- Description:
- Declares a new variable (myRowsToInsert) as of the Long data type.
- myRowsToInsert represents the number of rows to insert.
- Item: Dim myWorksheet As Worksheet.
- VBA construct: Dim statement.
- Description:
- Declares a new object variable (myWorksheet) to reference a Worksheet object.
- myWorksheet represents the worksheet you work with.
- Item: Dim iCounter As Long.
- VBA construct: Dim statement.
- Description:
- Declares a new variable (iCounter) as of the Long data type.
- iCounter represents a loop counter.
- Item: myFirstRow = 5.
- VBA construct: Assignment statement.
- Description: Assigns the value 5 to myFirstRow.
- Item: myNRows = 3.
- VBA construct: Assignment statement.
- Description: Assigns the value 3 to myNRows.
- Item: myRowsToInsert = 2.
- VBA construct: Assignment statement.
- Description: Assigns the value 2 to myRowsToInsert.
- Item: Set myWorksheet = Worksheets(“Insert M rows every N rows”).
- VBA constructs:
- Set statement.
- Workbooks.Worksheets property.
- Description: Assigns the Worksheet object representing the “Insert M rows every N rows” worksheet to myWorksheet.
- VBA constructs:
Lines #14 through #19: myLastRow = myWorksheet.Cells.Find( What:=”*”, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
- Item: myLastRow =.
- VBA construct: Assignment statement.
- Description: Assigns the value returned by items #2 through #9 below to myLastRow.
- Item: myWorksheet.Cells.
- VBA construct: Worksheet.Cells property.
- Description: Returns a Range object representing all cells on myWorksheet.
- Item: Find.
- VBA construct: Range.Find method.
- Description:
- Finds information in the cell range returned by item #2 above and returns a Range object representing the first cell where the information is found.
- In this example, the Range object Range.Find returns represents the last cell with data in last row with data in myWorksheet.
- Item: What:=”*”.
- VBA construct: What parameter of Range.Find method.
- Description: Specifies the data Range.Find searches for. The asterisk (*) is a wildcard and, therefore, Range.Find searches for any character sequence.
- Item: LookIn:=xlFormulas.
- VBA construct: LookIn parameter of Range.Find method.
- Description: Specifies that Range.Find looks in formulas (xlFormulas).
- Item: LookAt:=xlPart.
- VBA construct: LookAt parameter of Range.Find method.
- Description: Specifies that Range.Find looks at (and matches) a part (xlPart) of the search data.
- Item: SearchOrder:=xlByRows.
- VBA construct: SearchOrder parameter of Range.Find method.
- Description: Specifies that Range.Find searches by rows (xlByRows).
- Item: SearchDirection:=xlPrevious.
- VBA construct: SearchDirection parameter of Range.Find method.
- Description: Specifies that Range.Find searches for the previous match (xlPrevious).
- Item: Row.
- VBA construct: Range.Row property.
- Description:
- Returns the row number of the Range object returned by item #3 above.
- In this example, the number returned by Range.Row corresponds to the last row with data in myWorksheet.
Lines #20 and #22: For iCounter = myLastRow To (myFirstRow + myNRows) Step -1 | Next iCounter
- Item: For | Next iCounter.
- VBA construct: For… Next statement.
- Description:
- Repeats the statement inside the For… Next loop (line #21 below) a specific number of times.
- In this example:
- The macro starts on the last row of the data range as specified by item #2 below.
- Every iteration, the loop counter decreases by 1, as specified by item #4 below. Therefore, the macro moves to the previous row.
- The macro exits the loop after working with the row below the first block of rows you want to keep, as specified by item #3 below. Each block of rows has a number of rows equal to myNRows.
- In this example, myNRows equals 3. Therefore, the macro exits the loop after working with the fourth row in the data range.
- Item: iCounter = myLastRow.
- VBA constructs: Counter and Start of For… Next statement.
- Description: Specifies myLastRow as the initial value of the loop counter (iCounter).
- Item: To (myFirstRow + myNRows).
- VBA construct: End of For… Next statement.
- Description: Specifies the value represented by myFirstRow plus myNRows (myFirstRow + myNRows) as the final value of the loop counter.
- Item: Step -1.
- VBA construct: Step of For… Next statement.
- Description: Specifies that the loop counter (iCounter) decreases by 1 (-1) every loop iteration.
Line #21: If (iCounter – myFirstRow) Mod myNRows = 0 Then myWorksheet.Rows(iCounter & “:” & iCounter + myRowsToInsert – 1).Insert Shift:=xlShiftDown
- Item: If | Then.
- VBA construct: If… Then… Else statement.
- Description: Conditionally executes the statement specified by items #3 and #4 below, subject to condition specified by item #2 below being met.
- Item: (iCounter – myFirstRow) Mod myNRows = 0.
- VBA constructs:
- Condition of If… Then… Else statement.
- Numeric expression with Mod operator.
- Description:
- The Mod operator (Mod) (i) divides one number (iCounter – myFirstRow) by a second number (myNRows), and (ii) returns the remainder of the division.
- The condition ((iCounter – myFirstRow) Mod myNRows = 0) is met (returns True) if the remainder returned by Mod is 0.
- The condition is met (returns True) every time the macro loops through a row above which blank rows should be added.
- iCounter represents the number of the row through which the macro is currently looping.
- (iCounter – myFirstRow) is the number of rows (in the data range) above the row through which the macro is currently looping.
- ((iCounter – myFirstRow) Mod myNRows) equals 0 when the number of rows returned by (iCounter – myFirstRow) is a multiple of myNRows. This ensures that the number of rows left above the row through which the macro is currently looping can be appropriately separated into blocks of myNRows. In this example, myNRows equals 3. Therefore, the condition is met every 3 rows.
- VBA constructs:
- Item: myWorksheet.Rows(iCounter & “:” & iCounter + myRowsToInsert – 1).
- VBA constructs:
- Statements executed if the condition specified by item #2 above is met.
- Worksheet.Rows property.
- Description:
- Returns an object representing several rows of myWorksheet. The first row is represented by iCounter. The last row is represented by (iCounter + myRowsToInsert – 1).
- The number of rows Worksheet.Rows returns equals the number of rows to insert (myRowsToInsert).
- iCounter represents the number of the row through which the macro is currently looping.
- (iCounter + myRowsToInsert – 1) returns a row located a number of rows (myRowsToInsert – 1) below the row through which the macro is currently looping. In this example, myRowsToInsert equals 2. Therefore, (iCounter + myRowsToInsert – 1) returns a row located 1 (2 – 1) rows below the row through which the macro is currently looping.
- VBA constructs:
- Item: Insert.
- VBA construct: Range.Insert method.
- Description:
- Inserts new rows above the rows returned by item #3 above.
- The number of inserted rows is equal to the value of myRowsToInsert. This is calculated as follows:
lastRow# - firstRow# + 1 (iCounter + myRowsToInsert - 1) - iCounter + 1 = myRowsToInsert
In this example, if the current value of iCounter is 8:
(8 + 2 - 1) - 8 + 1 9 - 8 + 1 = 2
- Item: Shift:=xlShiftDown.
- VBA construct: Shift parameter of Range.Insert method.
- Description:
- Shifts rows down (xlShiftDown) to make space for the rows inserted by item #4 above.
- You can usually omit this parameter. By default, VBA decides how to shift the cells based on the range’s shape. When inserting a row, this usually results in Excel shifting the cells down.
Effects of Executing the Macro
The following GIF illustrates the results of executing this macro. As expected, VBA inserts 2 rows every 3 rows within the specified data range.