Entirerow vba excel описание


VBA Select

It is very common to find the .Select methods in saved macro recorder code, next to a Range object.

.Select is used to select one or more elements of Excel (as can be done by using the mouse) allowing further manipulation of them.

Selecting cells with the mouse:

Select with the Mouse

Selecting cells with VBA:

    'Range([cell1],[cell2])
    Range(Cells(1, 1), Cells(9, 5)).Select
    Range("A1", "E9").Select
    Range("A1:E9").Select

Each of the above lines select the range from «A1» to «E9».

Select with VBA


VBA Select CurrentRegion

If a region is populated by data with no empty cells, an option for an automatic selection is the CurrentRegion property alongside the .Select method.

CurrentRegion.Select will select, starting from a Range, all the area populated with data.

    Range("A1").CurrentRegion.Select

CurrentRegion

Make sure there are no gaps between values, as CurrentRegion will map the region through adjoining cells (horizontal, vertical and diagonal).

  Range("A1").CurrentRegion.Select

With all the adjacent data

CurrentRegion Data

Not all adjacent data

CurrentRegion Missing Data

«C4» is not selected because it is not immediately adjacent to any filled cells.


VBA ActiveCell

The ActiveCell property brings up the active cell of the worksheet.

In the case of a selection, it is the only cell that stays white.

A worksheet has only one active cell.

    Range("B2:C4").Select
    ActiveCell.Value = "Active"

ActiveCell

Usually the ActiveCell property is assigned to the first cell (top left) of a Range, although it can be different when the selection is made manually by the user (without macros).

ActiveCell Under

The AtiveCell property can be used with other commands, such as Resize.


VBA Selection

After selecting the desired cells, we can use Selection to refer to it and thus make changes:

    Range("A1:D7").Select
    Selection = 7

Example Selection

Selection also accepts methods and properties (which vary according to what was selected).

    Selection.ClearContents 'Deletes only the contents of the selection
    Selection.Interior.Color = RGB(255, 255, 0) 'Adds background color to the selection

Clear Selection

As in this case a cell range has been selected, the Selection will behave similarly to a Range. Therefore, Selection should also accept the .Interior.Color property.

RGB (Red Green Blue) is a color system used in a number of applications and languages. The input values for each color, in the example case, ranges from 0 to 255.


Selection FillDown

If there is a need to replicate a formula to an entire selection, you can use the .FillDown method

    Selection.FillDown

Before the FillDown

Before Filldown

After the FillDown

After FillDown

.FillDown is a method applicable to Range. Since the Selection was done in a range of cells (equivalent to a Range), the method will be accepted.

.FillDown replicates the Range/Selection formula of the first line, regardless of which ActiveCell is selected.

.FillDown can be used at intervals greater than one column (E.g. Range(«B1:C2»).FillDown will replicate the formulas of B1 and C1 to B2 and C2 respectively).


VBA EntireRow and EntireColumn

You can select one or multiple rows or columns with VBA.

    Range("B2").EntireRow.Select
    Range("C3:D3").EntireColumn.Select

Select EntireColumn

The selection will always refer to the last command executed with Select.

To insert a row use the Insert method.

    Range("A7").EntireRow.Insert
    'In this case, the content of the seventh row will be shifted downward

To delete a row use the Delete method.

    Range("A7").EntireRow.Delete
    'In this case, the content of the eighth row will be moved to the seventh

VBA Rows and Columns

Just like with the EntireRow and EntireColumn property, you can use Rows and Columns to select a row or column.

    Columns(5).Select
    Rows(3).Select

Select Rows

To hide rows:

    Range("A1:C3").Rows.Hidden = True

Hidden Cells

In the above example, rows 1 to 3 of the worksheet were hidden.


VBA Row and Column

Row and Column are properties that are often used to obtain the numerical address of the first row or first column of a selection or a specific cell.

    Range("A3:H30").Row 'Referring to the row; returns 3
    Range("B3").Column  'Referring to the column; returns 2

The results of Row and Column are often used in loops or resizing.



Consolidating Your Learning

Suggested Exercise



SuperExcelVBA.com is learning website. Examples might be simplified to improve reading and basic understanding. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. All Rights Reserved.

Excel ® is a registered trademark of the Microsoft Corporation.

© 2023 SuperExcelVBA | ABOUT

Protected by Copyscape

In this Article

  • Select Entire Rows or Columns
    • Select Single Row
    • Select Single Column
    • Select Multiple Rows or Columns
    • Select ActiveCell Row or Column
    • Select Rows and Columns on Other Worksheets
    • Is Selecting Rows and Columns Necessary?
  • Methods and Properties of Rows & Columns
    • Delete Entire Rows or Columns
    • Insert Rows or Columns
    • Copy & Paste Entire Rows or Columns
    • Hide / Unhide Rows and Columns
    • Group / UnGroup Rows and Columns
    • Set Row Height or Column Width
    • Autofit Row Height / Column Width
  • Rows and Columns on Other Worksheets or Workbooks
  • Get Active Row or Column

This tutorial will demonstrate how to select and work with entire rows or columns in VBA.

First we will cover how to select entire rows and columns, then we will demonstrate how to manipulate rows and columns.

Select Entire Rows or Columns

Select Single Row

You can select an entire row with the Rows Object like this:

Rows(5).Select

Or you can use EntireRow along with the Range or Cells Objects:

Range("B5").EntireRow.Select

or

Cells(5,1).EntireRow.Select

You can also use the Range Object to refer specifically to a Row:

Range("5:5").Select

Select Single Column

Instead of the Rows Object, use the Columns Object to select columns. Here you can reference the column number 3:

Columns(3).Select

or letter “C”, surrounded by quotations:

Columns("C").Select

Instead of EntireRow, use EntireColumn along with the Range or Cells Objects to select entire columns:

Range("C5").EntireColumn.Select

or

Cells(5,3).EntireColumn.Select

You can also use the Range Object to refer specifically to a column:

Range("B:B").Select

Select Multiple Rows or Columns

Selecting multiple rows or columns works exactly the same when using EntireRow or EntireColumn:

Range("B5:D10").EntireRow.Select

or

Range("B5:B10").EntireColumn.Select

However, when you use the Rows or Columns Objects, you must enter the row numbers or column letters in quotations:

Rows("1:3").Select

or

Columns("B:C").Select

Select ActiveCell Row or Column

To select the ActiveCell Row or Column, you can use one of these lines of code:

ActiveCell.EntireRow.Select

or

ActiveCell.EntireColumn.Select

Select Rows and Columns on Other Worksheets

In order to select Rows or Columns on other worksheets, you must first select the worksheet.

Sheets("Sheet2").Select
Rows(3).Select

The same goes for when selecting rows or columns in other workbooks.

Workbooks("Book6.xlsm").Activate
Sheets("Sheet2").Select
Rows(3).Select

Note: You must Activate the desired workbook. Unlike the Sheets Object, the Workbook Object does not have a Select Method.

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!

automacro

Learn More

Is Selecting Rows and Columns Necessary?

However, it’s (almost?) never necessary to actually select Rows or Columns. You don’t need to select a Row or Column in order to interact with them. Instead, you can apply Methods or Properties directly to the Rows or Columns. The next several sections will demonstrate different Methods and Properties that can be applied.

You can use any method listed above to refer to Rows or Columns.

Methods and Properties of Rows & Columns

Delete Entire Rows or Columns

To delete rows or columns, use the Delete Method:

Rows("1:4").Delete

or:

Columns("A:D").Delete

VBA Programming | Code Generator does work for you!

Insert Rows or Columns

Use the Insert Method to insert rows or columns:

Rows("1:4").Insert

or:

Columns("A:D").Insert

Copy & Paste Entire Rows or Columns

Paste Into Existing Row or Column

When copying and pasting entire rows or columns you need to decide if you want to paste over an existing row / column or if you want to insert a new row / column to paste your data.

These first examples will copy and paste over an existing row or column:

Range("1:1").Copy Range("5:5")

or

Range("C:C").Copy Range("E:E")

Insert & Paste

These next examples will paste into a newly inserted row or column.

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

Hide / Unhide Rows and Columns

To hide rows or columns set their Hidden Properties to True. Use False to hide the rows or columns:

'Hide Rows
Rows("2:3").EntireRow.Hidden = True

'Unhide Rows
Rows("2:3").EntireRow.Hidden = False

or

'Hide Columns
Columns("B:C").EntireColumn.Hidden = True

'Unhide Columns
Columns("B:C").EntireColumn.Hidden = False

Group / UnGroup Rows and Columns

If you want to Group rows (or columns) use code like this:

'Group Rows
Rows("3:5").Group

'Group Columns
Columns("C:D").Group

To remove the grouping use this code:

'Ungroup Rows
Rows("3:5").Ungroup

'Ungroup Columns
Columns("C:D").Ungroup

This will expand all “grouped” outline levels:

ActiveSheet.Outline.ShowLevels RowLevels:=8, ColumnLevels:=8

and this will collapse all outline levels:

ActiveSheet.Outline.ShowLevels RowLevels:=1, ColumnLevels:=1

Set Row Height or Column Width

To set the column width use this line of code:

Columns("A:E").ColumnWidth = 30

To set the row height use this line of code:

Rows("1:1").RowHeight = 30

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Autofit Row Height / Column Width

To Autofit a column:

Columns("A:B").Autofit

To Autofit a row:

Rows("1:2").Autofit

Rows and Columns on Other Worksheets or Workbooks

To interact with rows and columns on other worksheets, you must define the Sheets Object:

Sheets("Sheet2").Rows(3).Insert

Similarly, to interact with rows and columns in other workbooks, you must also define the Workbook Object:

Workbooks("book1.xlsm").Sheets("Sheet2").Rows(3).Insert

Get Active Row or Column

To get the active row or column, you can use the Row and Column Properties of the ActiveCell Object.

MsgBox ActiveCell.Row

or

MsgBox ActiveCell.Column

This also works with the Range Object:

MsgBox Range("B3").Column

Содержание

  1. VBA – Select (and work with) Entire Rows & Columns
  2. Select Entire Rows or Columns
  3. Select Single Row
  4. Select Single Column
  5. Select Multiple Rows or Columns
  6. Select ActiveCell Row or Column
  7. Select Rows and Columns on Other Worksheets
  8. VBA Coding Made Easy
  9. Is Selecting Rows and Columns Necessary?
  10. Methods and Properties of Rows & Columns
  11. Delete Entire Rows or Columns
  12. Insert Rows or Columns
  13. Copy & Paste Entire Rows or Columns
  14. Paste Into Existing Row or Column
  15. Insert & Paste
  16. Hide / Unhide Rows and Columns
  17. Group / UnGroup Rows and Columns
  18. Set Row Height or Column Width
  19. Autofit Row Height / Column Width
  20. Rows and Columns on Other Worksheets or Workbooks
  21. Get Active Row or Column
  22. VBA Code Examples Add-in
  23. Entirerow vba excel описание
  24. Примеры кода
  25. Скачать
  26. Типовые задачи
  27. Перебор ячеек диапазона (вариант 4)
  28. Работа с текущей областью
  29. Определение границ текущей области
  30. Выделение столбцов / строк текущей области
  31. Сброс форматирования диапазона
  32. Поиск последней строки столбца (вариант 1)
  33. Поиск последней строки столбца (вариант 2)
  34. Поиск «последней» ячейки листа
  35. Разбор клипо-генератора
  36. VBA Select, Row, Column
  37. VBA Select
  38. VBA Select CurrentRegion
  39. VBA ActiveCell
  40. VBA Selection
  41. Selection FillDown
  42. VBA EntireRow and EntireColumn
  43. VBA Rows and Columns
  44. VBA Row and Column
  45. Consolidating Your Learning
  46. FIRST STEPS
  47. FUNDAMENTALS
  48. RANGE
  49. USERFORM
  50. DEEPENING
  51. Report Error/Feedback
  52. Thank you!

VBA – Select (and work with) Entire Rows & Columns

In this Article

This tutorial will demonstrate how to select and work with entire rows or columns in VBA.

First we will cover how to select entire rows and columns, then we will demonstrate how to manipulate rows and columns.

Select Entire Rows or Columns

Select Single Row

You can select an entire row with the Rows Object like this:

Or you can use EntireRow along with the Range or Cells Objects:

You can also use the Range Object to refer specifically to a Row:

Select Single Column

Instead of the Rows Object, use the Columns Object to select columns. Here you can reference the column number 3:

or letter “C”, surrounded by quotations:

Instead of EntireRow, use EntireColumn along with the Range or Cells Objects to select entire columns:

You can also use the Range Object to refer specifically to a column:

Select Multiple Rows or Columns

Selecting multiple rows or columns works exactly the same when using EntireRow or EntireColumn:

However, when you use the Rows or Columns Objects, you must enter the row numbers or column letters in quotations:

Select ActiveCell Row or Column

To select the ActiveCell Row or Column, you can use one of these lines of code:

Select Rows and Columns on Other Worksheets

In order to select Rows or Columns on other worksheets, you must first select the worksheet.

The same goes for when selecting rows or columns in other workbooks.

Note: You must Activate the desired workbook. Unlike the Sheets Object, the Workbook Object does not have a Select Method.

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!

Is Selecting Rows and Columns Necessary?

However, it’s (almost?) never necessary to actually select Rows or Columns. You don’t need to select a Row or Column in order to interact with them. Instead, you can apply Methods or Properties directly to the Rows or Columns. The next several sections will demonstrate different Methods and Properties that can be applied.

You can use any method listed above to refer to Rows or Columns.

Methods and Properties of Rows & Columns

Delete Entire Rows or Columns

To delete rows or columns, use the Delete Method:

Insert Rows or Columns

Use the Insert Method to insert rows or columns:

Copy & Paste Entire Rows or Columns

Paste Into Existing Row or Column

When copying and pasting entire rows or columns you need to decide if you want to paste over an existing row / column or if you want to insert a new row / column to paste your data.

These first examples will copy and paste over an existing row or column:

Insert & Paste

These next examples will paste into a newly inserted row or column.

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:

Hide / Unhide Rows and Columns

To hide rows or columns set their Hidden Properties to True. Use False to hide the rows or columns:

Group / UnGroup Rows and Columns

If you want to Group rows (or columns) use code like this:

To remove the grouping use this code:

This will expand all “grouped” outline levels:

and this will collapse all outline levels:

Set Row Height or Column Width

To set the column width use this line of code:

To set the row height use this line of code:

Autofit Row Height / Column Width

To Autofit a row:

Rows and Columns on Other Worksheets or Workbooks

To interact with rows and columns on other worksheets, you must define the Sheets Object:

Similarly, to interact with rows and columns in other workbooks, you must also define the Workbook Object:

Get Active Row or Column

To get the active row or column, you can use the Row and Column Properties of the ActiveCell Object.

This also works with the Range Object:

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.

Источник

Entirerow vba excel описание

Продолжаем наш разговор про объект Excel Range , начатый в первой части. Разберём ещё несколько типовых задач и одну развлекательную. Кстати, в процессе написания второй части я дополнил и расширил первую, поэтому рекомендую её посмотреть ещё раз.

Примеры кода

Скачать

Типовые задачи

Перебор ячеек диапазона (вариант 4)

Для коллекции добавил четвёртый вариант перебора ячеек. Как видите, можно выбирать, как перебирается диапазон — по столбцам или по строкам. Обратите внимание на использование свойства коллекции Cells . Не путайте: свойство Cells рабочего листа содержит все ячейки листа, а свойство Cells диапазона ( Range ) содержит ячейки только этого диапазона. В данном случае мы получаем все ячейки столбца или строки.

Должен вас предупредить, что код, который вы видите в этом цикле статей — это код, написанный для целей демонстрации работы с объектной моделью Excel. Тут нет объявлений переменных, обработки ошибок и проверки условий, так как я специально минимизирую программы, пытаясь акцентировать ваше внимание целиком на обсуждаемом предмете — объекте Range .

Работа с текущей областью

Excel умеет автоматически определять текущую область вокруг активной ячейки. Соответствующая команда на листе вызывается через Ctrl + A . Через ActiveCell мы посредством свойства Worksheet легко выходим на лист текущей ячейки, а уже через него можем эксплуатировать свойство UsedRange , которое и является ссылкой на Range текущей области. Чтобы понять, какой диапазон мы получили, мы меняем цвет ячеек. Функция GetRandomColor не является стандартной, она определена в модуле файла примера.

Определение границ текущей области

Демонстрируем определение левого верхнего и правого нижнего углов диапазона текущей области. С левым верхним углом всё просто, так как координаты этой ячейки всегда доступны через свойства Row и Column объекта Range (не путать с коллекциями Rows и Columns !). А вот для определения второго угла приходится использовать конструкцию вида .Rows(.Rows.Count).Row , где .Rows.Count — количество строк в диапазоне UsedRange , .Rows(.Rows.Count) — это мы получили последнюю строку, и уже для этого диапазона забираем из свойства Row координату строки. Со столбцом — по аналогии. Также обратите внимание на использование оператора With . Как видите, оператор With , помимо сокращения кода, также позволяет отказаться от объявления отдельной объектной переменной через оператор Set , что очень удобно.

Выделение столбцов / строк текущей области

Тут нет ничего нового, мы всё это обсудили в предыдущем примере. Мы получаем ссылки на столбцы / строки, меняя их цвет для контроля результата работы кода.

Сброс форматирования диапазона

Для возвращения диапазона к каноническому стерильному состоянию очень просто и удобно использовать свойство Style , и присвоить ему имя стиля «Normal». Интересно, что все остальные стандартные стили в локализованном офисе имеют русские имена, а у этого стиля оставили англоязычное имя, что неплохо.

Поиск последней строки столбца (вариант 1)

Range имеет 2 свойства EntireColumn и EntireRow , возвращающие столбцы / строки, на которых расположился ваш диапазон, но возвращают их ЦЕЛИКОМ. То есть, если вы настроили диапазон на D5 , то Range(«D5»).EntireColumn вернёт вам ссылку на D:D , а EntireRow — на 5:5 .

Идём далее — свойство End возвращает вам ближайшую ячейку в определенном направлении, стоящую на границе непрерывного диапазона с данными. Как это работает вы можете увидеть, нажимая на листе комбинации клавиш Ctrl + стрелки . Кстати, это одна из самых полезных горячих клавиш в Excel. Направление задаётся стандартными константами xlUp , xlDown , xlToRight , xlToLeft .

Классическая задача у Excel программиста — определить, где кончается таблица или, в данном случае, конкретный столбец. Идея состоит в том, чтобы встать на последнюю ячейку столбца (строка 1048576) и, стоя в этой ячейке, перейти по Ctrl + стрелка вверх (что на языке VBA — End(xlUp) ).

Поиск последней строки столбца (вариант 2)

Ещё один вариант.

Поиск «последней» ячейки листа

Тут показывается, как найти на листе ячейку, ниже и правее которой находятся только пустые ячейки. Соответственно данные надо искать в диапазоне от A1 до этой ячейки. На эту ячейку можно перейти через Ctrl + End . Как этим воспользоваться в VBA показано ниже:

Разбор клипо-генератора

Ну, и в качестве развлечения и разрядки взгляните на код клипо-генератора, который генерирует цветные квадраты в заданных границах экрана. На некоторых это оказывает умиротворяющий эффект 🙂

По нашей теме в коде обращает на себя внимание использование свойства ReSize объекта Range . Как не трудно догадаться, свойство расширяет (усекает) текущий диапазон до указанных границ, при этом левый верхний угол диапазона сохраняет свои координаты. А также посмотрите на 2 последние строчки кода, реализующие очистку экрана. Там весьма показательно использован каскад свойств End и Offset .

Источник

VBA Select, Row, Column

VBA Select

It is very common to find the .Select methods in saved macro recorder code, next to a Range object.

.Select is used to select one or more elements of Excel (as can be done by using the mouse) allowing further manipulation of them.

Selecting cells with the mouse:

Selecting cells with VBA:

Each of the above lines select the range from «A1» to «E9».

VBA Select CurrentRegion

If a region is populated by data with no empty cells, an option for an automatic selection is the CurrentRegion property alongside the .Select method.

CurrentRegion.Select will select, starting from a Range , all the area populated with data.

Make sure there are no gaps between values, as CurrentRegion will map the region through adjoining cells (horizontal, vertical and diagonal).

With all the adjacent data

Not all adjacent data

«C4» is not selected because it is not immediately adjacent to any filled cells.

VBA ActiveCell

The ActiveCell property brings up the active cell of the worksheet.

In the case of a selection, it is the only cell that stays white.

A worksheet has only one active cell.

Usually the ActiveCell property is assigned to the first cell (top left) of a Range , although it can be different when the selection is made manually by the user (without macros).

The AtiveCell property can be used with other commands, such as Resize .

VBA Selection

After selecting the desired cells, we can use Selection to refer to it and thus make changes:

Selection also accepts methods and properties (which vary according to what was selected).

As in this case a cell range has been selected, the Selection will behave similarly to a Range . Therefore, Selection should also accept the .Interior.Color property.

RGB (Red Green Blue) is a color system used in a number of applications and languages. The input values for each color, in the example case, ranges from 0 to 255.

Selection FillDown

If there is a need to replicate a formula to an entire selection, you can use the .FillDown method

Before the FillDown

After the FillDown

.FillDown is a method applicable to Range . Since the Selection was done in a range of cells (equivalent to a Range ), the method will be accepted.

.FillDown replicates the Range / Selection formula of the first line, regardless of which ActiveCell is selected.

.FillDown can be used at intervals greater than one column (E.g. Range(«B1:C2»).FillDown will replicate the formulas of B1 and C1 to B2 and C2 respectively).

VBA EntireRow and EntireColumn

You can select one or multiple rows or columns with VBA.

The selection will always refer to the last command executed with Select .

To insert a row use the Insert method.

To delete a row use the Delete method.

VBA Rows and Columns

Just like with the EntireRow and EntireColumn property, you can use Rows and Columns to select a row or column.

In the above example, rows 1 to 3 of the worksheet were hidden.

VBA Row and Column

Row and Column are properties that are often used to obtain the numerical address of the first row or first column of a selection or a specific cell.

The results of Row and Column are often used in loops or resizing.

Consolidating Your Learning

Suggested Exercise

FIRST STEPS

FUNDAMENTALS

RANGE

USERFORM

DEEPENING

SuperExcelVBA.com is learning website. Examples might be simplified to improve reading and basic understanding. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. All Rights Reserved.

Excel ® is a registered trademark of the Microsoft Corporation.

Report Error/Feedback

Thank you!

Thank you for contributing. A message was sent reporting your comment.

Источник

Excel VBA Tutorial about how to insert rows with macrosIn 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.

Get immediate free access to the Excel VBA Insert Row workbook examples

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:

  1. Select the row or rows above which to insert the row or rows.
  2. Do one of the following:
    1. Right-click and select Insert.
    2. Go to Home > Insert > Insert Sheet Rows.
    3. Use the “Ctrl + Shift + +” keyboard shortcut.

Select rows; right-click; Insert

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:

  1. Range.Insert can insert a single cell or a cell range. For purposes of this VBA Tutorial, you’re interested in inserting entire rows.
  2. 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

  1. 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.
  2. 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

  1. 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.
  2. 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

  1. 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.
  2. 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

  1. 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.
  2. 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

  1. 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.

Get immediate free access to the Excel VBA Insert Row workbook examples

Each worksheet within the workbook contains a single data range. Most of the entries simply state “Data”.

Excel worksheet with 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

Worksheets.Rows.Insert Shift:=xlShiftDown

Process Followed by Macro

Identify row; Insert new row

VBA Statement Explanation

Worksheets(“Insert row”).Rows(6).Insert Shift:=xlShiftDown
  1. Item: Worksheets(“Insert row”).
    • VBA construct: Workbook.Worksheets property.
    • Description: Returns a Worksheet object representing the “Insert row” worksheet.
  2. Item: Rows(6).
    • VBA construct: Worksheets.Rows property.
    • Description: Returns a Range object representing row 6 of the worksheet returned by item #1 above.
  3. Item: Insert.
    • VBA construct: Range.Insert method.
    • Description: Inserts a new row above the row returned by item #2 above.
  4. 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.

Macro inserts new row in 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

Worksheets.Rows.Insert Shift:=xlShiftDown

Process Followed by Macro

Identify several rows; Insert new rows above

VBA Statement Explanation

Worksheets(“Insert row”).Rows(“11:15”).Insert Shift:=xlShiftDown
  1. Item: Worksheets(“Insert row”).
    • VBA construct: Workbook.Worksheets property.
    • Description: Returns a Worksheet object representing the “Insert row” worksheet.
  2. 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.
  3. 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
        
  4. 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.

Macro inserts multiple rows

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

Worksheets.Rows.Insert Shift:=xlShiftDown CopyOrigin:=xlFormatFromLeftOrAbove

Process Followed by Macro

Identify row; Insert row and use formatting from above

VBA Statement Explanation

Worksheets(“Insert row”).Rows(21).Insert Shift:=xlShiftDown, CopyOrigin:=xlFormatFromLeftOrAbove
  1. Item: Worksheets(“Insert row”).
    • VBA construct: Workbook.Worksheets property.
    • Description: Returns a Worksheet object representing the “Insert row” worksheet.
  2. Item: Rows(21).
    • VBA construct: Worksheet.Rows property.
    • Description: Returns a Range object representing row 21 of the worksheet returned by item #1 above.
  3. Item: Insert.
    • VBA construct: Range.Insert method.
    • Description: Inserts a new row above the row returned by item #2 above.
  4. 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.
  5. 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.

Macro inserts row with formatting from above

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

Worksheets.Rows.Insert Shift:=xlShiftDown, CopyOrigin:=xlFormatFromRightOrBelow

Process Followed by Macro

Identify row; Insert row and use formatting from row below

VBA Statement Explanation

Worksheets(“Insert row”).Rows(26).Insert Shift:=xlShiftDown, CopyOrigin:=xlFormatFromRightOrBelow
  1. Item: Worksheets(“Insert row”).
    • VBA construct: Workbook.Worksheets property.
    • Description: Returns a Worksheet object representing the “Insert row” worksheet.
  2. Item: Rows(26).
    • VBA construct: Worksheet.Rows property.
    • Description: Returns a Range object representing row 26 of the worksheet returned by item #1 above.
  3. Item: Insert.
    • VBA construct: Range.Insert method.
    • Description: Inserts a new row above the row returned by item #2 above.
  4. 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.
  5. 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.

Macro inserts row with formatting from below

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

Rows.Insert | Rows.ClearFormats

Process Followed by Macro

Identify row; Insert row; Clear formatting

VBA Statement Explanation

Lines #4 and #5: Dim myNewRowNumber As Long | myNewRowNumber = 31
  1. 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.
  2. Item: myNewRowNumber = 31.
    • VBA construct: Assignment statement.
    • Description: Assigns the value 31 to myNewRowNumber
Lines #6 and #9: With Worksheets(“Insert row”) | End With
  1. 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.
  2. 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
  1. 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.
  2. Item: Insert.
    • VBA construct: Range.Insert method.
    • Description: Inserts a new row above the row returned by item #1 above.
  3. 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
  1. 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.
  2. 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.

Macro inserts row without formatting

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

ActiveCell.Offset.EntireRow.Insert Shift:=xlShiftDown

Process Followed by Macro

Identify active cell; Move 1 row down; Identify row; Insert row

VBA Statement Explanation

ActiveCell.Offset(1).EntireRow.Insert Shift:=xlShiftDown
  1. Item: ActiveCell.
    • VBA construct: Application.ActiveCell property.
    • Description: Returns a Range object representing the active cell.
  2. 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.
  3. 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.
  4. Item: Insert.
    • VBA construct: Range.Insert method.
    • Description: Inserts a new row above the row returned by item #3 above.
  5. 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.

Macro inserts row below 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

Rows.Copy | Rows.Insert | CutCopyMode = False

Process Followed by Macro

Identify row | Copy | Identify row | Insert copied row | Cancel Cut or Copy mode

VBA Statement Explanation

Lines #4 and #7: With Worksheets(“Insert row”) | End With
  1. 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.
  2. Item: Worksheets(“Insert row”).
    • VBA construct: Workbook.Worksheets property.
    • Description: Returns a Worksheet object representing the “Insert row” worksheet.
Line #5: .Rows(45).Copy
  1. 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).
  2. 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
  1. 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).
  2. 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.
  3. 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
  1. 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.

Macro inserts copied row

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

For iCounter myLastRow to myFirstRow + 1 Step -1 | Rows.Insert

Process Followed by Macro

Identify range; go to last row; Insert row; go to previous row; loop

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”)
  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. Item: myFirstRow = 5.
    • VBA construct: Assignment statement.
    • Description: Assigns the value 5 to myFirstRow.
  6. 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.
Lines #10 through #15: myLastRow = myWorksheet.Cells.Find( What:=”*”, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
  1. Item: myLastRow =.
    • VBA construct: Assignment statement.
    • Description: Assigns the value returned by items #2 through #9 below to myLastRow.
  2. Item: myWorksheet.Cells.
    • VBA construct: Worksheet.Cells property.
    • Description: Returns a Range object representing all cells on myWorksheet.
  3. 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.
  4. 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.
  5. Item: LookIn:=xlFormulas.
    • VBA construct: LookIn parameter of Range.Find method.
    • Description: Specifies that Range.Find looks in formulas (xlFormulas).
  6. 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.
  7. Item: SearchOrder:=xlByRows.
    • VBA construct: SearchOrder parameter of Range.Find method.
    • Description: Specifies that Range.Find searches by rows (xlByRows).
  8. Item: SearchDirection:=xlPrevious.
    • VBA construct: SearchDirection parameter of Range.Find method.
    • Description: Specifies that Range.Find searches for the previous match (xlPrevious).
  9. 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
  1. 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.
  2. Item: iCounter = myLastRow.
    • VBA construct: Counter and Start of For… Next statement.
    • Description: Specifies myLastRow as the initial value of the loop counter (iCounter).
  3. 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.
  4. 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
  1. 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.
  2. 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.
  3. 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.

Macro inserts blank rows between rows

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

For iCounter = myLastRow To myFirstRow + myNRows Step -1 | If multiple of myNRows Then Rows.Insert

Process Followed by Macro

Identify data range; go to last row; conditional test; insert row; loop

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”)
  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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.
  7. Item: myFirstRow = 5.
    • VBA construct: Assignment statement.
    • Description: Assigns the value 5 to myFirstRow.
  8. Item: myNRows = 3.
    • VBA construct: Assignment statement.
    • Description: Assigns the value 3 to myNRows.
  9. Item: myRowsToInsert = 2.
    • VBA construct: Assignment statement.
    • Description: Assigns the value 2 to myRowsToInsert.
  10. 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.
Lines #14 through #19: myLastRow = myWorksheet.Cells.Find( What:=”*”, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
  1. Item: myLastRow =.
    • VBA construct: Assignment statement.
    • Description: Assigns the value returned by items #2 through #9 below to myLastRow.
  2. Item: myWorksheet.Cells.
    • VBA construct: Worksheet.Cells property.
    • Description: Returns a Range object representing all cells on myWorksheet.
  3. 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.
  4. 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.
  5. Item: LookIn:=xlFormulas.
    • VBA construct: LookIn parameter of Range.Find method.
    • Description: Specifies that Range.Find looks in formulas (xlFormulas).
  6. 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.
  7. Item: SearchOrder:=xlByRows.
    • VBA construct: SearchOrder parameter of Range.Find method.
    • Description: Specifies that Range.Find searches by rows (xlByRows).
  8. Item: SearchDirection:=xlPrevious.
    • VBA construct: SearchDirection parameter of Range.Find method.
    • Description: Specifies that Range.Find searches for the previous match (xlPrevious).
  9. 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
  1. 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.
  2. Item: iCounter = myLastRow.
    • VBA constructs: Counter and Start of For… Next statement.
    • Description: Specifies myLastRow as the initial value of the loop counter (iCounter).
  3. 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.
  4. 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
  1. 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.
  2. 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.
  3. 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.
  4. 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
        
  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 #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.

Macro inserts rows every number of rows

The VBA Range Object

The Excel Range Object is an object in Excel VBA that represents a cell, row, column, a selection of cells or a 3 dimensional range. The Excel Range is also a Worksheet property that returns a subset of its cells.

Worksheet Range

The Range is a Worksheet property which allows you to select any subset of cells, rows, columns etc.

Dim r as Range 'Declared Range variable

Set r = Range("A1") 'Range of A1 cell

Set r = Range("A1:B2") 'Square Range of 4 cells - A1,A2,B1,B2

Set r= Range(Range("A1"), Range ("B1")) 'Range of 2 cells A1 and B1

Range("A1:B2").Select 'Select the Cells A1:B2 in your Excel Worksheet

Range("A1:B2").Activate 'Activate the cells and show them on your screen (will switch to Worksheet and/or scroll to this range.

Select a cell or Range of cells using the Select method. It will be visibly marked in Excel:
range select cell

Working with Range variables

The Range is a separate object variable and can be declared as other variables. As the VBA Range is an object you need to use the Set statement:

Dim myRange as Range 
'...
Set myRange = Range("A1") 'Need to use Set to define myRange

The Range object defaults to your ActiveWorksheet. So beware as depending on your ActiveWorksheet the Range object will return values local to your worksheet:

Range("A1").Select
'...is the same as...
ActiveSheet.Range("A1").Select

You might want to define the Worksheet reference by Range if you want your reference values from a specifc Worksheet:

Sheets("Sheet1").Range("A1").Select 'Will always select items from Worksheet named Sheet1

The ActiveWorkbook is not same to ThisWorkbook. Same goes for the ActiveSheet. This may reference a Worksheet from within a Workbook external to the Workbook in which the macro is executed as Active references simply the currently top-most worksheet. Read more here

Range properties

The Range object contains a variety of properties with the main one being it’s Value and an the second one being its Formula.

A Range Value is the evaluated property of a cell or a range of cells. For example a cell with the formula =10+20 has an evaluated value of 20.
A Range Formula is the formula provided in the cell or range of cells. For example a cell with a formula of =10+20 will have the same Formula property.

'Let us assume A1 contains the formula "=10+20"

Debug.Print Range("A1").Value 'Returns: 30

Debug.Print Range("A1").Formula 'Returns: =10+20

Other Range properties include:
Work in progress

Worksheet Cells

A Worksheet Cells property is similar to the Range property but allows you to obtain only a SINGLE CELL, based on its row and column index. Numbering starts at 1:
cells select cell

The Cells property is in fact a Range object not a separate data type.
Excel facilitates a Cells function that allows you to obtain a cell from within the ActiveSheet, current top-most worksheet.

Cells(2,2).Select 'Selects B2
'...is the same as...
ActiveSheet.Cells(2,2).Select 'Select B2

Cells are Ranges which means they are not a separate data type:

Dim myRange as Range
Set myRange = Cells(1,1) 'Cell A1

Range Rows and Columns

As we all know an Excel Worksheet is divided into Rows and Columns. The Excel VBA Range object allows you to select single or multiple rows as well as single or multiple columns. There are a couple of ways to obtain Worksheet rows in VBA:

Getting an entire row or column

entirerow rangeTo get and entire row of a specified Range you need to use the EntireRow property. Although, the function’s parameters suggest taking both a RowIndex and ColumnIndex it is enough just to provide the row number. Row indexing starts at 1.
entirecolumn rangeTo get and entire column of a specified Range you need to use the EntireColumn property. Although, the function’s parameters suggest taking both a RowIndex and ColumnIndex it is enough just to provide the column number. Column indexing starts at 1.

Range("B2").EntireRows(1).Hidden = True 'Gets and hides the entire row 2

Range("B2").EntireColumns(1).Hidden = True 'Gets and hides the entire column 2

The three properties EntireRow/EntireColumn, Rows/Columns and Row/Column are often misunderstood so read through to understand the differences.

Get a row/column of a specified range

range rows functionIf you want to get a certain row within a Range simply use the Rows property of the Worksheet. Although, the function’s parameters suggest taking both a RowIndex and ColumnIndex it is enough just to provide the row number. Row indexing starts at 1.
range columns functionSimilarly you can use the Columns function to obtain any single column within a Range. Although, the function’s parameters suggest taking both a RowIndex and ColumnIndex actually the first argument you provide will be the column index. Column indexing starts at 1.

Rows(1).Hidden = True 'Hides the first row in the ActiveSheet
'same as
ActiveSheet.Rows(1).Hidden = True

Columns(1).Hidden = True 'Hides the first column in the ActiveSheet
'same as
ActiveSheet.Columns(1).Hidden = True

To get a range of rows/columns you need to use the Range function like so:

Range(Rows(1), Rows(3)).Hidden = True 'Hides rows 1:3
'same as
Range("1:3").Hidden = True
'same as 
ActiveSheet.Range("1:3").Hidden = True

Range(Columns(1), Columns(3)).Hidden = True 'Hides columns A:C
'same as
Range("A:C").Hidden = True
'same as 
ActiveSheet.Range("A:C").Hidden = True

Get row/column of specified range

The above approach assumed you want to obtain only rows/columns from the ActiveSheet – the visible and top-most Worksheet. Usually however, you will want to obtain rows or columns of an existing Range. Similarly as with the Worksheet Range property, any Range facilitates the Rows and Columns property.

Dim myRange as Range
Set myRange = Range("A1:C3")

myRange.Rows.Hidden = True 'Hides rows 1:3
myRange.Columns.Hidden = True 'Hides columns A:C

Set myRange = Range("C10:F20")
myRange.Rows(2).Hidden = True 'Hides rows 11
myRange.Columns(3).Hidden = True 'Hides columns E

Getting a Ranges first row/column number

Aside from the Rows and Columns properties Ranges also facilitate a Row and Column property which provide you with the number of the Ranges first row and column.

Set myRange = Range("C10:F20")

'Get first row number
Debug.Print myRange.Row 'Result: 10
'Get first column number
Debug.Print myRange.Column 'Result: 3

Converting Column number to Excel Column

This is an often question that turns up – how to convert a column number to a string e.g. 100 to “CV”.

Function GetExcelColumn(columnNumber As Long)
    Dim div As Long, colName As String, modulo As Long
    div = columnNumber: colName = vbNullString

    Do While div > 0
        modulo = (div - 1) Mod 26
        colName = Chr(65 + modulo) & colName
        div = ((div - modulo) / 26)
    Loop

    GetExcelColumn = colName
End Function

Range Cut/Copy/Paste

Cutting and pasting rows is generally a bad practice which I heavily discourage as this is a practice that is moments can be heavily cpu-intensive and often is unaccounted for.

Copy function

Range copy functionThe Copy function works on a single cell, subset of cell or subset of rows/columns.

'Copy values and formatting from cell A1 to cell D1
Range("A1").Copy Range("D1")

'Copy 3x3 A1:C3 matrix to D1:F3 matrix - dimension must be same
Range("A1:C3").Copy Range("D1:F3")

'Copy rows 1:3 to rows 4:6
Range("A1:A3").EntireRow.Copy Range("A4")

'Copy columns A:C to columns D:F
Range("A1:C1").EntireColumn.Copy Range("D1")

The Copy function can also be executed without an argument. It then copies the Range to the Windows Clipboard for later Pasting.

Cut function

range cut functionThe Cut function, similarly as the Copy function, cuts single cells, ranges of cells or rows/columns.

'Cut A1 cell and paste it to D1
Range("A1").Cut Range("D1")

'Cut 3x3 A1:C3 matrix and paste it in D1:F3 matrix - dimension must be same
Range("A1:C3").Cut Range("D1:F3")

'Cut rows 1:3 and paste to rows 4:6
Range("A1:A3").EntireRow.Cut Range("A4")

'Cut columns A:C and paste to columns D:F
Range("A1:C1").EntireColumn.Cut Range("D1")

The Cut function can be executed without arguments. It will then cut the contents of the Range and copy it to the Windows Clipboard for pasting.

Cutting cells/rows/columns does not shift any remaining cells/rows/columns but simply leaves the cut out cells empty

PasteSpecial function

range pastespecial functionThe Range PasteSpecial function works only when preceded with either the Copy or Cut Range functions. It pastes the Range (or other data) within the Clipboard to the Range on which it was executed.

Syntax

The PasteSpecial function has the following syntax:

PasteSpecial( Paste, Operation, SkipBlanks, Transpose)

The PasteSpecial function can only be used in tandem with the Copy function (not Cut)

Parameters

Paste
The part of the Range which is to be pasted. This parameter can have the following values:

Parameter Constant Description
xlPasteSpecialOperationAdd 2 Copied data will be added with the value in the destination cell.
xlPasteSpecialOperationDivide 5 Copied data will be divided with the value in the destination cell.
xlPasteSpecialOperationMultiply 4 Copied data will be multiplied with the value in the destination cell.
xlPasteSpecialOperationNone -4142 No calculation will be done in the paste operation.
xlPasteSpecialOperationSubtract 3 Copied data will be subtracted with the value in the destination cell.

Operation
The paste operation e.g. paste all, only formatting, only values, etc. This can have one of the following values:

Name Constant Description
xlPasteAll -4104 Everything will be pasted.
xlPasteAllExceptBorders 7 Everything except borders will be pasted.
xlPasteAllMergingConditionalFormats 14 Everything will be pasted and conditional formats will be merged.
xlPasteAllUsingSourceTheme 13 Everything will be pasted using the source theme.
xlPasteColumnWidths 8 Copied column width is pasted.
xlPasteComments -4144 Comments are pasted.
xlPasteFormats -4122 Copied source format is pasted.
xlPasteFormulas -4123 Formulas are pasted.
xlPasteFormulasAndNumberFormats 11 Formulas and Number formats are pasted.
xlPasteValidation 6 Validations are pasted.
xlPasteValues -4163 Values are pasted.
xlPasteValuesAndNumberFormats 12 Values and Number formats are pasted.

SkipBlanks
If True then blanks will not be pasted.

Transpose
Transpose the Range before paste (swap rows with columns).

PasteSpecial Examples

'Cut A1 cell and paste its values to D1
Range("A1").Copy
Range("D1").PasteSpecial
 
'Copy 3x3 A1:C3 matrix and add all the values to E1:G3 matrix (dimension must be same)
Range("A1:C3").Copy 
Range("E1:G3").PasteSpecial xlPasteValues, xlPasteSpecialOperationAdd

Below an example where the Excel Range A1:C3 values are copied an added to the E1:G3 Range. You can also multiply, divide and run other similar operations.
PasteSpecial example - Copy and Add

Paste

The Paste function allows you to paste data in the Clipboard to the actively selected Range. Cutting and Pasting can only be accomplished with the Paste function.

'Cut A1 cell and paste its values to D1
Range("A1").Cut
Range("D1").Select
ActiveSheet.Paste
 
'Cut 3x3 A1:C3 matrix and paste it in D1:F3 matrix - dimension must be same
Range("A1:C3").Cut 
Range("D1:F3").Select
ActiveSheet.Paste
 
'Cut rows 1:3 and paste to rows 4:6
Range("A1:A3").EntireRow.Cut 
Range("A4").Select
ActiveSheet.Paste
 
'Cut columns A:C and paste to columns D:F
Range("A1:C1").EntireColumn.Cut 
Range("D1").Select
ActiveSheet.Paste

Range Clear/Delete

The Clear function

The Clear function clears the entire content and formatting from an Excel Range. It does not, however, shift (delete) the cleared cells.

Range("A1:C3").Clear

Excel Range Clear function example

The Delete function

Range Delete functionThe Delete function deletes a Range of cells, removing them entirely from the Worksheet, and shifts the remaining Cells in a selected shift direction.
Although the manual Delete cell function provides 4 ways of shifting cells. The VBA Delete Shift values can only be either be xlShiftToLeft or xlShiftUp.

'If Shift omitted, Excel decides - shift up in this case
Range("B2").Delete 

'Delete and Shift remaining cells left
Range("B2").Delete xlShiftToLeft  

'Delete and Shift remaining cells up
Range("B2").Delete xlShiftTop

'Delete entire row 2 and shift up
Range("B2").EntireRow.Delete

'Delete entire column B and shift left
Range("B2").EntireRow.Delete

Excel Range Delete - shifting cells

Traversing Ranges

Traversing cells is really useful when you want to run an operation on each cell within an Excel Range. Fortunately this is easily achieved in VBA using the For Each or For loops.

Dim cellRange As Range
    
For Each cellRange In Range("A1:C3")
  Debug.Print cellRange.Value
Next cellRange

Although this may not be obvious, beware of iterating/traversing the Excel Range using a simple For loop. For loops are not efficient on Ranges. Use a For Each loop as shown above. This is because Ranges resemble more Collections than Arrays. Read more on For vs For Each loops here

Traversing the UsedRange

Excel Range - Worksheet UsedRangeEvery Worksheet has a UsedRange. This represents that smallest rectangle Range that contains all cells that have or had at some point values. In other words if the further out in the bottom, right-corner of the Worksheet there is a certain cell (e.g. E8) then the UsedRange will be as large as to include that cell starting at cell A1 (e.g. A1:E8). In Excel you can check the current UsedRange hitting CTRL+END. In VBA you get the UsedRange like this:

ActiveSheet.UsedRange
'same as
UsedRange

You can traverse through the UsedRange like this:

Dim cellRange As Range
    
For Each cellRange In UsedRange
  Debug.Print "Row: " & cellRange.Row & ", Column: " & cellRange.Column
Next cellRange

The UsedRange is a useful construct responsible often for bloated Excel Workbooks. Often delete unused Rows and Columns that are considered to be within the UsedRange can result in significantly reducing your file size. Read also more on the XSLB file format here

Range Addresses

The Excel Range Address property provides a string value representing the Address of the Range.
Excel Range Address property

Syntax

Below the syntax of the Excel Range Address property:

Address( [RowAbsolute], [ColumnAbsolute], [ReferenceStyle], [External], [RelativeTo] )

Parameters

RowAbsolute
Optional. If True returns the row part of the reference address as an absolute reference. By default this is True.

$D$10:$G$100 'RowAbsolute is set to True
$D10:$G100 'RowAbsolute is set to False

ColumnAbsolute
Optional. If True returns the column part of the reference as an absolute reference. By default this is True.

$D$10:$G$100 'ColumnAbsolute is set to True
D$10:G$100 'ColumnAbsolute is set to False

ReferenceStyle
Optional. The reference style. The default value is xlA1. Possible values:

Constant Value Description
xlA1 1 Default. Use xlA1 to return an A1-style reference
xlR1C1 -4150 Use xlR1C1 to return an R1C1-style reference

External
Optional. If True then property will return an external reference address, otherwise a local reference address will be returned. By default this is False.

$A$1 'Local
[Book1.xlsb]Sheet1!$A$1 'External

RelativeTo
Provided RowAbsolute and ColumnAbsolute are set to False, and the ReferenceStyle is set to xlR1C1, then you must include a starting point for the relative reference. This must be a Range variable to be set as the reference point.

Merged Ranges

Excel Range Merge functionMerged cells are Ranges that consist of 2 or more adjacent cells. To Merge a collection of adjacent cells run Merge function on that Range.

The Merge has only a single parameter – Across, a boolean which if True will merge cells in each row of the specified range as separate merged cells. Otherwise the whole Range will be merged. The default value is False.

Merge examples

To merge the entire Range:

'This will turn of any alerts warning that values may be lost
Application.DisplayAlerts = False

Range("B2:C3").Merge

This will result in the following:
Excel Range Merged cells
To merge just the rows set Across to True.

'This will turn of any alerts warning that values may be lost
Application.DisplayAlerts = False

Range("B2:C3").Merge True

This will result in the following:
Excel Range Merged cells across rows

Remember that merged Ranges can only have a single value and formula. Hence, if you merge a group of cells with more than a single value/formula only the first value/formula will be set as the value/formula for your new merged Range

Checking if Range is merged

To check if a certain Range is merged simply use the Excel Range MergeCells property:

Range("B2:C3").Merge

Debug.Print Range("B2").MergeCells 'Result: True

The MergeArea

The MergeArea is a property of an Excel Range that represent the whole merge Range associated with the current Range. Say that $B$2:$C$3 is a merged Range – each cell within that Range (e.g. B2, C3..) will have the exact same MergedArea. See example below:

Range("B2:C3").Merge
Debug.Print Range("B2").MergeArea.Address 'Result: $B$2:$C$3

Named Ranges

Named Ranges are Ranges associated with a certain Name (string). In Excel you can find all your Named Ranges by going to Formulas->Name Manager. They are very useful when working on certain values that are used frequently through out your Workbook. Imagine that you are writing a Financial Analysis and want to use a common Discount Rate across all formulas. Just the address of the cell e.g. “A2”, won’t be self-explanatory. Why not use e.g. “DiscountRate” instead? Well you can do just that.

Creating a Named Range

Named Ranges can be created either within the scope of a Workbook or Worksheet:

Dim r as Range
'Within Workbook
Set r = ActiveWorkbook.Names.Add("NewName", Range("A1"))
'Within Worksheet
Set r = ActiveSheet.Names.Add("NewName", Range("A1"))

This gives you flexibility to use similar names across multiple Worksheets or use a single global name across the entire Workbook.

Listing all Named Ranges

You can list all Named Ranges using the Name Excel data type. Names are objects that represent a single NamedRange. See an example below of listing our two newly created NamedRanges:

Call ActiveWorkbook.Names.Add("NewName", Range("A1"))
Call ActiveSheet.Names.Add("NewName", Range("A1"))

Dim n As Name
For Each n In ActiveWorkbook.Names
  Debug.Print "Name: " & n.Name & ", Address: " & _
       n.RefersToRange.Address & ", Value: "; n.RefersToRange.Value
Next n

'Result:
'Name: Sheet1!NewName, Address: $A$1, Value:  1 
'Name: NewName, Address: $A$1, Value:  1 

SpecialCells

SpecialCells are a very useful Excel Range property, that allows you to select a subset of cells/Ranges within a certain Range.

Syntax

The SpecialCells property has the following syntax:

SpecialCells( Type, [Value] )

Parameters

Type
The type of cells to be returned. Possible values:

Constant Value Description
xlCellTypeAllFormatConditions -4172 Cells of any format
xlCellTypeAllValidation -4174 Cells having validation criteria
xlCellTypeBlanks 4 Empty cells
xlCellTypeComments -4144 Cells containing notes
xlCellTypeConstants 2 Cells containing constants
xlCellTypeFormulas -4123 Cells containing formulas
xlCellTypeLastCell 11 The last cell in the used range
xlCellTypeSameFormatConditions -4173 Cells having the same format
xlCellTypeSameValidation -4175 Cells having the same validation criteria
xlCellTypeVisible 12 All visible cells

Value
If Type is equal to xlCellTypeConstants or xlCellTypeFormulas this determines the types of cells to return e.g. with errors.

Constant Value
xlErrors 16
xlLogical 4
xlNumbers 1
xlTextValues 2

SpecialCells examples

Get Excel Range with Constants

This will return only cells with constant cells within the Range C1:C3:

For Each r In Range("A1:C3").SpecialCells(xlCellTypeConstants)
  Debug.Print r.Value
Next r

Search for Excel Range with Errors

For Each r In ActiveSheet.UsedRange.SpecialCells(xlCellTypeFormulas, xlErrors)
  Debug.Print r.Address
Next r

Excel VBA Referencing Ranges — Range, Cells, Item, Rows & Columns Properties; Offset; ActiveCell; Selection; Insert

You can refer to or access a worksheet range using properties and methods of the Range object. A Range Object refers to a cell or a range of cells. It can be a row, a column or a selection of cells comprising of one or more rectangular / contiguous blocks of cells. One of the most important aspects in vba coding is referencing and using Ranges within a Worksheet. This section (divided into 2 parts) covers various properties and methods for referencing, accessing & using ranges, divided under the following chapters.

Excel VBA Referencing Ranges — Range, Cells, Item, Rows & Columns Properties; Offset; ActiveCell; Selection; Insert:

Range Property, Cells / Item / Rows / Columns Properties, Offset & Relative Referencing, Cell Address;

Activate & Select Cells; the ActiveCell & Selection;

Entire Row & Entire Column Properties, Inserting Cells/Rows/Columns using the Insert Method;

Excel VBA Refer to Ranges — Union & Intersect; Resize; Areas, CurrentRegion, UsedRange & End Properties; SpecialCells Method:

Ranges — Union & Intersect;

Resize a Range;

Referencing — Contiguous Block(s) of Cells, Range of Contiguous Data, Cells Meeting a Specified Criteria, Used Range, Cell at the End of a Block / Region, Last Used Row or Column;


Related Links:

Working with Objects in Excel VBA

Excel VBA Application Object, the Default Object in Excel

Excel VBA Workbook Object, working with Workbooks in Excel

Microsoft Excel VBA — Worksheets

Excel VBA Custom Classes and Objects


——————————————————————————————-

Contents:

Range Property, Cells / Item / Rows / Columns Properties, Offset & Relative Referencing, Cell Address

Activate & Select Cells; the ActiveCell & Selection

Entire Row & Entire Column Properties, Inserting Cells/Rows/Columns using the Insert Method

——————————————————————————————-

Range Property, Cells / Item / Rows / Columns Properties, Offset & Relative Referencing, Cell Address

A Range Object refers to a cell or a range of cells. It can be a row, a column or a selection of cells comprising of one or more rectangular / contiguous blocks of cells. A Range object is always with reference to a specific worksheet, and Excel currently does not support Range objects spread over multiple worksheets.

Range object refers to a single cell:

Dim rng As Range
Set rng = Range(«A1»)

Range object refers to a block of contiguous cells:

Dim rng As Range
Set rng = Range(«A1:C3»)

Range object refers to a row:

Dim rng As Range
Set rng = Rows(1)

Range object refers to multiple columns:

Dim rng As Range
Set rng = Columns(«A:C»)

Range object refers to 2 or more blocks of contiguous cells — using the ‘Union method’ & ‘Selection’ (these have been explained in detail later in this section).

Union method:

Dim rng1 As Range, rng2 As Range, rngUnion As Range
‘set a contiguous block of cells as the first range:
Set rng1 = Range(«A1:B2»)
‘set another contiguous block of cells as the second range:
Set rng2 = Range(«D3:E4»)
‘assign a variable (range object) to represent the union of the 2 ranges, using the Union method:
Set rngUnion = Union(rng1, rng2)
‘set interior color for the range which is the union of 2 range objects:
rngUnion.Interior.Color = vbYellow

Selection property:

‘select 2 contiguous block of cells, using the Select method:
Range(«A1:B2,D3:E4»).Select
‘perform action (set interior color of cells to yellow) on the Selection, which is a Range object:
Selection.Interior.Color = vbYellow

Range property of the Worksheet object ie. Worksheet.Range Property. Syntax: WorksheetObject.Range(Cell1, Cell2). You have an option to use only the Cell1 argument and in this case it will have to be a A1-style reference to a range which can include a range operator (colon) or the union operator (comma), or the reference to a range can be a defined name. Examples of using this type of reference are Worksheets(«Sheet1»).Range(«A1») which refers to cell A1; or Worksheets(«Sheet1»).Range(«A1:B3») which refers to the cells A1, A2, A3, B1, B2 & B3. When both the Cell1 & Cell2 arguments are used (cell1 and cell2 are Range objects), these refer to the cells at the top-left corner and the lower-right corner of the range (ie. the start and end cells of the range), and these arguments can be a single cell, an entire row or column or a single named cell. An example of using this type of reference is Worksheets(«Sheet1»).Range(Cells(1, 1), Cells(3, 2)) which refers to the cells A1, A2, A3, B1, B2 & B3. Omitting the object qualifier will default to the active sheet viz. using the code Range(«A1») will return cell A1 of the active sheet, and will be the same as using Application.Range(«A1») or ActiveSheet.Range(«A1»).

Range property of the Range object: Use the Range.Range property [Syntax: RangeObject.Range(Cell1,Cell2)] for relative referencing ie. to access a range relative to a range object. For example, Worksheets(«Sheet1»).Range(«C5:E8»).Range(«A1») will refer to Range(«C5») and Worksheets(«Sheet1»).Range(«C5:E8»).Range(«B2») will refer to Range(«D6»).

Shortcut Range Reference: As compared to using the Range property, you can also use a shorter code to refer to a range by using square brackets to enclose an A1-style reference or a name. While using square brackets, you do not type the Range word or wrap the range in quotation marks to make it a string. Using square brackets is similar to applying the Evaluate method of the Application object. The Range property or the Evaluate method use a string argument which enables you to manipulate the string with vba code, whereas using the square brackets will be inflexible in this respect. Examples: using [A1].Value = 5 is equivalent to using Range(«A1»).Value = 5; using [A1:A3,B2:B4,C3:D5].Interior.Color = vbRed is equivalent to Range(«A1:A3,B2:B4,C3:D5»).Interior.Color = vbRed; and with named ranges, [Score].Interior.Color = vbBlue is equivalent to Range(«Score»).Interior.Color = vbBlue. Using square brackets only enables reference to fixed ranges which is a significant shortcoming. Using the Range property enables you to manipulate the string argument with vba code so that you can use variables to refer to a dynamic range, as illustrated below:

Sub DynamicRangeVariable()
‘using a variable to refer a dynamic range.

Dim i As Integer

‘enters the text «Hello» in each cell from B1 to B5:
For i = 1 To 5
Range(«B» & i) = «Hello»
Next

End Sub

The Cells Property returns a Range object referring to all cells in a worksheet or a range, as it can be used with respect to an Application object, a Worksheet object or a Range object. Application.Cells Property refers to all cells in the active worksheet. You can use the code Application.Cells or omit the object qualifier (this property is a member of ‘globals’) and use the code Cells to refer to all cells of the active worksheet. The Worksheet.Cells Property (Syntax: WorksheetObject.Cells) refers to all cells of a specified worksheet. Use the code Worksheets(«Sheet1»).Cells to refer to all cells of worksheet named «Sheet1». Use the Range.Cells Property ro refer to cells in a specified range — (Syntax: RangeObject.Cells). This property can be used as Range(«A1:B5»).Cells, however using the word cells in this case is immaterial because with or without this word the code will refer to the range A1:B5. To refer to a specific cell, use the Item property of the Range object (as explained in detail below) by specifying the relative row and column positions after the Cells keyword, viz. Worksheets(«Sheet1»).Cells.Item(2, 3) refers to range C2 and Worksheets(«Sheet1»).Range(«C2»).Cells(2, 3) will refer to range E3. Because the Item property is the Range object’s default property you can omit the Item word word and use the code Worksheets(«Sheet1»).Cells(2, 3) which also refers to range C2. You may find it preferable in some cases to use Worksheets(«Sheet1»).Cells(2, 3) over Worksheets(«Sheet1»).Range(«C2») because variables for the row and column can easily be used therein.

Item property of the Range object: Use the Range.Item Property to return a range as offset to the specified range. Syntax: RangeObject.Item(RowIndex, ColumnIndex). The Item word can be omitted because Item is the Range object’s default property. It is necessary to specify the RowIndex argument while ColumnIndex is optional. RowIndex is the index number of the cell, starting with 1 and increasing from left to right and then down. Worksheets(«Sheet1»).Cells.Item(1) or Worksheets(«Sheet1»).Cells(1) refers to range A1 (the top-left cell in the worksheet), Worksheets(«Sheet1»).Cells(2) refers to range B1 (cell next to the right of the top-left cell). While using a single-parameter reference of the Item property (ie. RowIndex), if index exceeds the number of columns in the specified range, the reference will wrap to successive rows within the range columns. Omitting the object qualifier will default to active sheet. Cells(16385) refers to range A2 of the active sheet in Excel 2007 which has 16384 columns, and Cells(16386) refers to range B2, and so on. Also note that RowIndex and ColumnIndex are offsets and relative to the specified Range (ie. relative to the top-left corner of the specified range). Both Range(«B3»).Item(1) and Range(«B3:D6»).Item(1) refer to range B3. The following refer to range D4, the sixth cell in the range: Range(«B3:D6»).Item(6) or Range(«B3:D6»).Cells(6) or Range(«B3:D6»)(6). ColumnIndex refers to the column number of the cell, can be a number starting with 1 or can be a string starting with the letter «A». Worksheets(«Sheet1»).Cells(2, 3) and Worksheets(«Sheet1»).Cells(2, «C») both refer to range C2 wherein the RowIndex is 2 and ColumnIndex is 3 (column C). Range(«C2»).Cells(2, 3) refers to range E3 in the active sheet, and Range(«C2»).Cells(4, 5) refers to range G5 in the active sheet. Using Range(«C2»).Item(2, 3) and Range(«C2»).Item(4, 5) has the same effect and will refer to range E3 & range G5 respectively. Using Range(«C2:D3»).Cells(2, 3) and Range(«C2:D3»).Cells(4, 5) will also refer to range E3 & range G5 respectively. Omitting the Item or Cells word — Range(«C2:D3»)(2, 3) and Range(«C2:D3»)(4, 5) also refers to range E3 & range G5 respectively. It is apparant here that you can refer to and return cells outside the original specified range, using the Item property.

Columns property of the Worksheet object: Use the Worksheet.Columns Property (Syntax: WorksheetObject.Columns) to refer to all columns in a worksheet  which are returned as a Range object. Example: Worksheets(«Sheet1»).Columns will return all columns of the worksheet; Worksheets(«Sheet1»).Columns(1) returns the first column (column A) in the worksheet; Worksheets(«Sheet1»).Columns(«A») returns the first column (column A); Worksheets(«Sheet1»).Columns(«A:C») returns the columns A, B & C; and so on. Omitting the object qualifier will default to the active sheet viz. using the code Columns(1) will return the first column of the active sheet, and will be the same as using Application.Columns(1).

Columns property of the Range object: Use the Range.Columns Property (Syntax: RangeObject.Columns) to refer to columns in a specified range. Example1: color cells from all columns of the specified range ie. B2 to D4: Worksheets(«Sheet1»).Range(«B2:D4»).Columns.Interior.Color = vbYellow. Example2: color cells from first column of the range only ie. B2 to B4: Worksheets(«Sheet1»).Range(«B2:D4»).Columns(1).Interior.Color = vbGreen. If the specified range object contains multiple areas, the columns from the first area only will be returned by this property (Areas property has been explained in detail later in this section). Take the example of 2 areas in the specified range, first area being «B2:D4» and the second area being «F3:G6» — the following code will color cells from first column of the first area only ie. cells B2 to B4: Worksheets(«Sheet1»).Range(«B2:D4, F3:G6»).Columns(1).Interior.Color = vbRed. Omitting the object qualifier will default to active sheet — following will apply color to column A of the ActiveSheet: Columns(1).Interior.Color = vbRed.

Use the Worksheet.Rows Property (Syntax: WorksheetObject.Rows) to refer to all rows in a worksheet  which are returned as a Range object. Example: Worksheets(«Sheet1»).Rows will return all rows of the worksheet; Worksheets(«Sheet1»).Rows(1) returns the first row (row one) in the worksheet; Worksheets(«Sheet1»).Rows(3) returns the third row (row three) in the worksheet; Worksheets(«Sheet1»).Rows(«1:3») returns the first 3 rows; and so on. Omitting the object qualifier will default to the active sheet viz. using the code Rows(1) will return the first row of the active sheet, and will be the same as using Application.Rows(1).

Use the Range.Rows Property (Syntax: RangeObject.Rows) to refer to rows in a specified range. Example1: color cells from all rows of the specified range ie. B2 to D4: Worksheets(«Sheet1»).Range(«B2:D4»).Rows.Interior.Color = vbYellow. Example2: color cells from first row of the range only ie. B2 to D2: Worksheets(«Sheet1»).Range(«B2:D4»).Rows(1).Interior.Color = vbGreen. If the specified range object contains multiple areas, the rows from the first area only will be returned by this property (Areas property has been explained in detail later in this section). Take the example of 2 areas in the specified range, first area being «B2:D4» and the second area being «F3:G6» — the following code will color cells from first row of the first area only ie. cells B2 to D2: Worksheets(«Sheet1»).Range(«B2:D4, F3:G6»).Rows(1).Interior.Color = vbRed. Omitting the object qualifier will default to active sheet — following will apply color to row one of the ActiveSheet: Rows(1).Interior.Color = vbRed.

To refer to a range as offset from a specified range, use the Range.Offset Property. Syntax: RangeObject.Offset(RowOffset, ColumnOffset). Both arguments are optional to specify. The RowOffset argument specifies the number of rows by which the specified range is offset — negative values indicating upward offset and positive values indicating downward offset, with default value being 0. The ColumnOffset argument specifies the number of columns by which the specified range is offset — negative values indicating left offset and positive values indicating right offset, with default value being 0. Examples: Range(«C5»).Offset(1, 2) offsets 1 row & 2 columns and refers to Range E6, Range(«C5:D7»).Offset(1, -2) offsets 1 row downward & 2 columns to the left and refers to Range (A6:B8).

Accessing a worksheet range, with vba code:-

Referencing a single cell:

Enter the value 10 in the cell A1 of the worksheet named «Sheet1» (omitting to mention a property with the Range object will assume the Value property, as shown below):

Worksheets(«Sheet1»).Range(«A1»).Value = 10

Worksheets(«Sheet1»).Range(«A1») = 10

Enter the value of 10 in range C2 of the active worksheet — using Cells(row, column) where row is the row index and column is the column index:

ActiveSheet.Cells(2, 3).Value = 10

Referencing a range of cells:

Enter the value 10 in the cells A1, A2, A3, B1, B2 & B3 (wherein the cells refer to the upper-left corner & lower-right corner of the range) of the active sheet:

ActiveSheet.Range(«A1:B3»).Value = 10

ActiveSheet.Range(«A1», «B3»).Value = 10

ActiveSheet.Range(Cells(1, 1), Cells(3, 2)) = 10

Enter the value 10 in the cells A1 & B3 of worksheet named «Sheet1»:

Worksheets(«Sheet1»).Range(«A1,B3»).Value = 10

Set the background color (red) for cells B2, B3, C2, C3, D2, D3 & H7 of worksheet named «Sheet3»:

ActiveWorkbook.Worksheets(«Sheet3»).

Range(«B2:D3,H7»).Interior.Color = vbRed

Enter the value 10 in the Named Range «Score» of the active worksheet, viz. you can name the Range(«B2:B3») as «Score» to insert 10 in the cells B2 & B3:

Range(«Score»).Value = 10

ActiveSheet.Range(«Score»).Value = 10

Select all the cells of the active worksheet:

ActiveSheet.Cells.Select

Cells.Select

Set the font to «Times New Roman» & the font size to 11, for all the cells of the active worksheet in the active workbook:

ActiveWorkbook.ActiveSheet.Cells.Font.Name = «Times New Roman»

ActiveSheet.Cells.Font.Size = 11

Cells.Font.Size = 11

Referencing Row(s) or Column(s):

Select all the Rows of active worksheet:

ActiveSheet.Rows.Select

Enter the value 10 in the Row number 2 (ie. every cell in second row), of worksheet named «Sheet1»:

Worksheets(«Sheet1»).Rows(2).Value = 10

Select all the Columns of the active worksheet:

ActiveSheet.Columns.Select

Columns.Select

Enter the value 10 in the Column number 3 (ie. every cell in column C), of the active worksheet:

ActiveSheet.Columns(3).Value = 10

Columns(«C»).Value = 10

Enter the value 10 in Column numbers 1, 2 & 3 (ie. every cell in columns A to C), of worksheet named «Sheet1»:

Worksheets(«Sheet1»).Columns(«A:C»).Value = 10

Relative Referencing:

Inserts the value 10 in Range C5 — reference starts from upper-left corner of the defined Range:

Range(«C5:E8»).Range(«A1») = 10

Inserts the value 10 in Range D6 — reference starts from upper-left corner of the defined Range:

Range(«C5:E8»).Range(«B2») = 10

Inserts the value 10 in Range E6 — offsets 1 row & 2 columns, using the Offset property:

Range(«C5»).Offset(1, 2) = 10

Inserts the value 10 in Range(«F7:H10») — offsets 2 rows & 3 columns, using the Offset property:

Range(«C5:E8»).Offset(2, 3) = 10

Example 1 — Using Range, Cells, Columns & Rows property — refer Image 1:

Sub CellsColumnsRowsProperty()
‘using Range, Cells, Columns & Rows property — refer Image 1:

Dim ws As Worksheet
Dim rng As Range
Dim r As Integer, c As Integer, n As Integer, i As Integer, j As Integer

‘set worksheet:
Set ws = Worksheets(«Sheet1»)
‘activate worksheet:
ws.activate

‘enter numbers starting from 1 in each row, for a 5 row & 5 column range (A1:E5):

For r = 1 To 5

n = 1

For c = 1 To 5

Cells(r, c).Value = n

n = n + 1

Next c

Next r

‘set range to A1:E5, wherein the numbers have been entered as above:
Set rng = Range(Cells(1, 1), Cells(5, 5))

‘set background color of each even number column to yellow and of each odd number column to green:

For i = 1 To 5

If i Mod 2 = 0 Then

rng.Columns(i).Interior.Color = vbYellow
Else

rng.Columns(i).Interior.Color = vbGreen

End If

Next i

‘set font color to red and set font to bold for of even number rows:

For j = 1 To 5

If j Mod 2 = 0 Then

rng.Rows(j).Font.Bold = True

rng.Rows(j).Font.Color = vbRed

End If

Next j

‘set font for all cells of the range to italics:
rng.Cells.Font.Italic = True

End Sub

To return the number of the first row in a range, use the Range.Row Property. If the specified range contains multiple areas, this property will return the number of the first row in the first area (Areas property has been explained in detail later in this section). Syntax: RangeObject.Row. To return the number of the first column in a range, use the Range.Column Property. If the specified range contains multiple areas, this property will return the number of the first column in the first area. Syntax: RangeObject.Column.

Examples:

Get the number of the first row in the specified range — returns 4:

MsgBox ActiveSheet.Range(«B4»).Row

MsgBox Worksheets(«Sheet1»).Range(«B4:D7»).Row

Get the number of the first column in the specified range — returns 2:

MsgBox ActiveSheet.Range(«B4:D7»).Column

Get the number of the last row in the specified range — returns 7:

Explanation: Range(«B4:D7»).Rows.Count returns 4 (the number of rows in the range). Range(«B4:D7»).Rows(Range(«B4:D7»).Rows.Count) or Range(«B4:D7»).Rows(4), returns the last row in the specified range.

MsgBox Range(«B4:D7»).Rows(Range(«B4:D7»).

Rows.Count).Row

Example 2: Using Row Property, Column Property & Rows Property, determine row number & column number, and alternate rows — refer Image 2.

Sub RowColumnProperty()
‘Using Row Property, Column Property & Rows Property, determine row number & column number, and alternate rows — refer Image 2.

Dim rng As Range, cell As Range
Dim i As Integer

Set rng = Worksheets(«Sheet1»).Range(«B4:D7»)

‘enter its row number & column number within each cell in the specified range:

For Each cell In rng

cell.Value = cell.Row & «,» & cell.Column

Next

‘set background color of each alternate row of the specified range:

For i = 1 To rng.Rows.count

If i Mod 2 = 1 Then

rng.Rows(i).Interior.Color = vbGreen

Else

rng.Rows(i).Interior.Color = vbYellow

End If

Next

End Sub

Also refer to Example 23, of using the End & Row properties to determine the last used row or column with data.

You can get a Range reference in vba language by using the Range.Address Property, which returns the address of a Range as a string value. This property is read-only.

Examples of using the Address Property:

Returns $B$2:

MsgBox Range(«B2»).Address

Returns $B$2,$C$3:

MsgBox Range(«B2,C3»).Address

Returns $A$1:$B$2,$C$3,$D$4:

Dim strRng As String
Range(«A1:B2,C3,D4»).Select
strRng = Selection.Address
MsgBox strRng

Returns $B2:

MsgBox Range(«B2»).Address(RowAbsolute:=False)

Returns B$2:

MsgBox Range(«B2»).Address(ColumnAbsolute:=False)

Returns R2C2:

MsgBox Range(«B2»).Address(ReferenceStyle:=xlR1C1)

Includes the worksheet (active sheet — «Sheet1») & workbook («Book1.xlsm») name, and returns [Book1.xlsm]Sheet1!$B$2:

MsgBox Range(«B2»).Address(External:=True)

Returns R[1]C[-1] — Range(«B2») is 1 row and -1 columns relative to Range(«C1»):

MsgBox Range(«B2»).Address(RowAbsolute:=False, ColumnAbsolute:=False, ReferenceStyle:=xlR1C1, RelativeTo:=Range(«C1»))

Returns RC[-2] — Range(«A1») is 0 row and -2 columns relative to Range(«C1»):

MsgBox Cells(1, 1).Address(RowAbsolute:=False, ColumnAbsolute:=False, ReferenceStyle:=xlR1C1, RelativeTo:=Range(«C1»))

Activate & Select Cells; the ActiveCell & Selection

The Select method (of the Range object) is used to select a cell or a range of cells in a worksheet — Syntax: RangeObject.Select. Ensure that the worksheet wherein the Select method is applied to select cells, is the active sheet. The ActiveCell Property (of the Application object) returns a single active cell (Range object) in the active worksheet. Remember that the ActiveCell property will not work if the active sheet is not a worksheet. When a cell(s) is selected in the active window, the Selection property (of the Application object) returns a Range object representing all cells which are currently selected in the active worksheet. A Selection may consist of a single cell or a range of multiple cells, but there will only be one active cell within it, which is returned by using the ActiveCell property. When only a single cell is selected, the ActiveCell property returns this cell. On selecting multiple cells using the Select method, the first referenced cell becomes the active cell, and thereafter you can change the active cell using the Activate method. Both the ActiveCell Property & the Selection property are read-only, and not specifying the Application object qualifier viz. Application.ActiveCell or ActiveCell, Application.Selection or Selection, will have the same effect. To activate a single cell within the current selection, use the Activate Method (of the Range object) — Syntax: RangeObject.Activate, and this activated cell is returned by using the ActiveCell property.

We have discussed above that a Selection may consist of a single cell or a range of multiple cells, whereas there can be only one active cell within the Selection. When you activate a cell outside the current selection, the activated cell becomes the only selected cell. You can also use the Activate method to specify a range of multiple cells, but in effect only a single cell will be activated, and this activated cell will be the top-left corner cell of the range specified in the method. If this top-left cell lies within the selection, the current selection will not change, but if this top-left cell lies outside the selection, then the specified range in the Activate method becomes the new selection.

See below codes which illustrate the concepts of ActiveCell and Selection.

Selection containing a range of cells, and the active cell:

‘selects range C1:F5:
Range(«C1:F5»).Select
‘returns C1, the first referenced cell, as the active cell:
MsgBox ActiveCell.Address

Selection containing a range of cells, and the active cell:

‘selects range C1:F5:
Range(«F5:C1»).Select
‘returns C1, the first referenced cell, as the active cell:
MsgBox ActiveCell.Address

Selection containing a range of cells, and the active cell:

‘selects range C1:F5:
Range(«C5:F1»).Select
‘returns C1, the first referenced cell, as the active cell:
MsgBox ActiveCell.Address

Activate a cell within the current selection:

‘selects range B6:F10:
Range(«B6:F10»).Select
‘returns B6, the first referenced cell, as the active cell:
MsgBox ActiveCell.Address

‘selection remains same — range B6:F10, but the active cell is now C8:
Range(«C8»).Activate
MsgBox ActiveCell.Address

Activate a cell outside the current selection:

‘selects range B6:F10:
Range(«B6:F10»).Select
‘returns B6, the first referenced cell, as the active cell:
MsgBox ActiveCell.Address

‘both the selection and the active cell is now A2:
Range(«A2»).Activate
MsgBox ActiveCell.Address

Select a cell within the current selection:

‘selects range B6:F10:
Range(«B6:F10»).Select
‘returns B6, the first referenced cell, as the active cell:
MsgBox ActiveCell.Address

‘both the selection and the active cell is now C8:
Range(«C8»).Select
MsgBox ActiveCell.Address

Activate a range of cells whose top-left cell is within the current selection:

‘selects range B6:F10 — refer Image 3a:
Range(«B6:F10»).Select
‘returns B6, the first referenced cell, as the active cell:
MsgBox ActiveCell.Address

‘selection remains same — range B6:F10, but the active cell is now C8 — refer Image 3b:
Range(«C8:G12»).Activate
MsgBox ActiveCell.Address

Activate a range of cells whose top-left cell is outside the current selection:

‘selects range B6:F10 — refer Image 3a:
Range(«B6:F10»).Select
‘returns B6, the first referenced cell, as the active cell:
MsgBox ActiveCell.Address

‘selection range changes to range B1:F8, and the active cell is now B1 — refer Image 3c:
Range(«B1:F8»).Activate
MsgBox ActiveCell.Address

Using the Application.Selection Property returns the selected object wherein the selection determines the returned object type. Where the selection is a range of cells, this property returns a Range object, and this Selection — which is a Range object — can comprise of a single cell, or multiple cells or multiple non-contiguous ranges. And as mentioned above, the Select method (of the Range object) is used to select a cell or a range of cells in a worksheet. Therefore, after selecting a range, you can perform actions on the selection of cells by using the Selection object. See below illustration. 

Sub SelectionObject()

‘select cells in the active sheet using the Range.Select method:

Range(«A1:B3,D6»).Select

‘perform action (set interior color of cells to red) on the Selection, which is a Range object:

Selection.Interior.Color = vbRed

End Sub

Entire Row & Entire Column Properties, Inserting Cells/Rows/Columns using the Insert Method

Use the Range.EntireRow Property to return an entire row or rows within which the specific range is contained. Using this property returns a Range object referring to the entire row(s). Syntax: RangeObject.EntireRow. Use the Range.EntireColumn Property to return an entire column or columns within which the specific range is contained. Using this property returns a Range object referring to the entire column(s). Syntax: RangeObject.EntireColumn.

Examples of using the EntireRow & EntireColumn Properties

Selects row no. 2:

Range(«A2»).EntireRow.Select

Selects row nos. 2, 3 & 4:

Range(«A2:C4»).EntireRow.Select

Enters value 3 in range A3 ie. in the first cell of row no. 3:

Cells(3, 4).EntireRow.Cells(1, 1).Value = 3

Selects column A:

Range(«A2»).EntireColumn.Select

Selects columns A to C:

Range(«A2:C4»).EntireColumn.Select

Enters value 4 in range D1 ie. in the first cell of column no. 4:

Cells(3, 4).EntireColumn.Cells(1, 1).Value = 4

Use the Range.Insert Method to insert a cell or a range of cells in a worksheet. Syntax: RangeObject.Insert(Shift, CopyOrigin). Both arguments are optional to specify. When you insert cell(s) the other cells are shifted to make way, and you can set a value for the Shift argument to determine the direction in which the other cells are shifted — specifying xlShiftDown (value -4121) will shift the cells down, and xlShiftToRight (value -4161) shifts the cells to the right. Omitting this argument will decide the shift direction based on the shape of the range. Specifying xlFormatFromLeftOrAbove (value 0) for the CopyOrigin argument will copy the format for inserted cell(s) from the above cells or cells to the left, and specifying xlFormatFromRightOrBelow (value 1) will copy format from the below cells or cells to the right.

Illustrating Range.Insert Method — for start data refer Image 4a:

Shifts cells down and copies formatting of inserted cell from above cell — refer image 4b:

Range(«B2»).Insert

Shifts cells to the right and copies formatting of inserted cells from cells to the left — refer image 4c:

Range(«B2:C4»).Insert

Shifts cells down and copies formatting of inserted cells from above cells — refer image 4d:

Range(«B2:D3»).Insert

Shifts cells down and copies formatting of inserted cells from below cells — refer image 4e:

Range(«B2:D3»).Insert CopyOrigin:=xlFormatFromRightOrBelow

Shifts cells to the right and copies formatting of inserted cells from cells to the left — refer image 4f:

Range(«B2:D3»).Insert shift:=xlShiftToRight

Shifts cells to the right and copies formatting of inserted cells from cells to the right — refer image 4g:

Range(«B2:D3»).Insert shift:=xlShiftToRight, CopyOrigin:=xlFormatFromRightOrBelow

Inserts 2 rows — row no 2 & 3 — and copies formatting of inserted rows from above cells — refer image 4h:

Range(«B2:D3»).EntireRow.Insert

Below are some illustrations of inserting entire row(s) or column(s) dynamically in a worksheet.

Example 3: Insert row or column — specify the row / column to insert.

Sub InsertRowColumn()
‘Insert row or column — specify the row / column to insert:

Dim ws As Worksheet
Set ws = Worksheets(«Sheet1»)

‘NOTE: each of the below codes need to be run individually.

‘specify the exact row number to insert — insert a row as row no 12:
ws.Rows(12).Insert

‘specify the range below which to insert a row — insert a row below range C3 ie. as row no 4.
ws.Range(«C3»).EntireRow.Offset(1, 0).Insert

‘specify the exact column number to insert — insert a column as column no 4:
ws.Columns(4).Insert

‘specify the range to the right of which to insert a column — insert a column to the right of range C3 ie. as column no 4.

ws.Range(«C3»).EntireColumn.Offset(0, 1).Insert

End Sub

Example 4: Insert row(s) after a specified value is found.

Sub InsertRow1()
‘insert row(s) after a specified value is found:

Dim ws As Worksheet
Dim rngFind As Range, rngSearch As Range, rngLastCell As Range
Dim lFindRow As Long

Set ws = Worksheets(«Sheet1»)

‘find a value after which to insert a row:
Set rngSearch = ws.Range(«A1:E100»)
‘begin search AFTER the last cell in search range (this will start serach from the first cell in search range):
Set rngLastCell = rngSearch.Cells(rngSearch.Cells.count)
Set rngFind = rngSearch.Find(What:=«ExcelVBA», After:=rngLastCell, LookIn:=xlValues, lookat:=xlWhole)

‘exit procedure if value not found:

If Not rngFind Is Nothing Then

lFindRow = rngFind.Row

MsgBox lFindRow

Else

MsgBox «Value not found!»

Exit Sub

End If

‘NOTE: each of the below codes need to be run individually.

‘if value found is in row no 12, one row will be inserted below as row no 13:
ws.Cells(lFindRow + 1, 1).EntireRow.Insert

‘if value found is in row no 12, one row will be inserted 3 rows below (as row no 15):
ws.Cells(lFindRow + 3, 1).EntireRow.Insert

‘if value found is in row no 12, one row will be inserted 3 rows below (as row no 15):
ws.Cells(lFindRow, 1).Offset(3).EntireRow.Insert

‘if value found is in row no 12, 3 rows will be inserted above (as row nos 12, 13 & 14) and the value found row 12 will be pushed down to row 15:
ws.Cells(lFindRow, 1).EntireRow.Resize(3).Insert
‘alternate:
ws.Range(Cells(lFindRow, 1), Cells(lFindRow + 2, 1)).EntireRow.Insert
‘alternate:
ws.Rows(lFindRow & «:» & lFindRow + 2).EntireRow.Insert Shift:=xlDown

‘if value found is in row no 12, 3 rows will be inserted below (as row nos 13, 14 & 15) and the value found row 12 will remain at the same position:
ws.Cells(lFindRow + 1, 1).EntireRow.Resize(3).Insert
‘alternate:
ws.Range(ws.Cells(lFindRow + 1, 1), ws.Cells(lFindRow + 3, 1)).EntireRow.Insert

‘if value found is in row no 12, 3 rows will be inserted after row no 13 (as row nos 14, 15 & 16) and existing rows 12 & 13 will remain at the same position:

ws.Cells(lFindRow + 2, 1).EntireRow.Resize(3).Insert

End Sub

Example 5: Insert a row, n rows above the last used row.

Sub InsertRow2()
‘insert a row, n rows above the last used row

Dim ws As Worksheet
Dim lRowsC As Long

Set ws = Worksheets(«Sheet1»)

‘determine the last used row in a column (column A):
lRowsC = ws.Cells(Rows.count, «A»).End(xlUp).Row
MsgBox lRowsC

‘set n to the no of rows above the last used row:
n = 5

‘check if there are enough rows before the last used row, else you will get an error:

If lRowsC >= n Then

‘insert a row, n rows above the last used row — if last used row is no 5 before insertion, then insert as row no 1 and the last used row will become no 6 (similarly, if last used row is 27, then insert as row no 23) :

ws.Rows(lRowsC).Offset(-n + 1, 0).EntireRow.Insert

Else

MsgBox «Not enough rows before the last used row!»

End If

End Sub

Example 6: Insert a row each time the searched value is found in a range.

For live code of this example, click to download excel file.

Sub InsertRow3()
‘search value in a range and insert a row each time the value is found.
‘you can set the search range with the variable rngSearch in below code — the code will look within this range to find the value below which row is to be inserted.

Dim ws As Worksheet
Dim rngFind As Range, rngSearch As Range, rngLastCell As Range
Dim strAddress As String

Set ws = Worksheets(«Sheet1»)

‘set search range:
Set rngSearch = ws.Range(«A1:K100»)
MsgBox «Searching for ‘ExcelVBA’ within range: » & rngSearch.Address
‘begin search AFTER the last cell in search range
Set rngLastCell = rngSearch.Cells(rngSearch.Cells.count)

‘find value in specified range, starting search AFTER the last cell in search range:
Set rngFind = rngSearch.Find(What:=«ExcelVBA», After:=rngLastCell, LookIn:=xlValues, lookat:=xlWhole)

If rngFind Is Nothing Then

MsgBox «Value not found!»

Exit Sub

Else

‘save cell address of first value found:

strAddress = rngFind.Address

Do

‘find next occurrence of value:

Set rngFind = rngSearch.FindNext(After:=rngFind)

‘insert row below when value is found (if value is found twice in a row, then 2 rows will be inserted):

rngFind.Offset(1).EntireRow.Insert

‘loop till reaching the first value found range:

Loop While rngFind.Address <> strAddress

End If

End Sub

Example 7: Insert rows (user-defined number) within consecutive values found in a column — refer Images 5a & 5b.

For live code of this example, click to download excel file.

Sub InsertRow4()
‘insert rows (user-defined number) wherever 2 consecutive values are found in a column.
‘set column number in which 2 consecutive values are checked to insert rows, using the variable lCellColumn in below code.
‘set row number from where to start searching consecutive values, using the variable lCellRow in below code.
‘refer Image 5a which shows raw data, and Image 5b after this procedure is executed — a single row (lRowsInsert value entered as 1 in input box) is inserted where consecutive values appear in column 1:

Dim ws As Worksheet
Dim lLastUsedRow As Long, lRowsInsert As Long, lCellRow As Long, lCellColumn As Long
Dim rng As Range

Set ws = Worksheets(«Sheet1»)
ws.Activate

‘set column number in which 2 consecutive values are checked to insert rows:
lCellColumn = 1
‘set row number from where to start searching consecutive values:
lCellRow = 1

‘determine the last used row in the column (column no. lCellColumn):
lLastUsedRow = Cells(Rows.count, lCellColumn).End(xlUp).Row

‘enter number of rows to insert between 2 consecutive values:
lRowsInsert = InputBox(«Enter number of rows to insert»)

If lRowsInsert < 1 Then

MsgBox «Error — please enter a value equal to or greater than 1»

Exit Sub

End If

MsgBox «This code will insert » & lRowsInsert & » rows, wherever consecutive values are found in column number » & lCellColumn & «, starting search from row number » & lCellRow

‘loop till the row number equals the last used row (ie. loop right till the end value in the column):

Do While lCellRow < lLastUsedRow

Set rng = Cells(lCellRow, lCellColumn)

‘in case of 2 consecutive values:

If rng <> «» And rng.Offset(1, 0) <> «» Then

‘enter the user-defined number of rows:

Range(rng.Offset(1, 0), rng.Offset(lRowsInsert, 0)).EntireRow.Insert

lCellRow = lCellRow + lRowsInsert + 1

‘determine the last used row — it is dynamic and changes on insertion of rows:

lLastUsedRow = Cells(Rows.count, lCellColumn).End(xlUp).Row

‘alternate method to determine the last used row, when number of rows inserted is fixed — this is faster than using End(xlUp):

‘lLastUsedRow = lLastUsedRow + lRowsInsert + 1

‘MsgBox lLastUsedRow

Else

lCellRow = lCellRow + 1

End If

Loop

End Sub

Понравилась статья? Поделить с друзьями:
  • Entirerow hidden vba excel
  • Eplan спецификация изделий в excel
  • Entirerow excel это что
  • Epica martyr of the free word
  • Entire row vba excel