VBA: How to Insert Row with Formatting


You can use the following syntax in VBA to insert a row that has the same formatting as the row above it:

Sub insertRowWithFormatting()

ActiveCell.Offset(1).EntireRow.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromRightOrAbove
ActiveCell.EntireRow.Copy
ActiveCell.Offset(1).EntireRow.PasteSpecial xlPasteFormats

Application.CutCopyMode = False

End Sub

This particular macro will insert one row below the currently selected cell with the exact same formatting as the cells in the currently selected row.

Note: The line Application.CutCopyMode = False specifies that the cut and copy mode should be turned off after running the macro.

The following example shows how to use this syntax in practice.

Related: How to Insert Multiple Rows Using VBA

Example: Insert Row with Formatting in VBA

Suppose we have the following dataset in Excel that contains information about various basketball players:

Suppose we would like to insert a row below row 2 with the exact same formatting.

We can create the following macro to do so:

Sub insertRowWithFormatting()

ActiveCell.Offset(1).EntireRow.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromRightOrAbove
ActiveCell.EntireRow.Copy
ActiveCell.Offset(1).EntireRow.PasteSpecial xlPasteFormats

Application.CutCopyMode = False

End Sub

We can then select cell A2 and then run this macro.

When we run this macro, we receive the following output:

Notice that the new row we inserted has the exact same formatting as the cells in row 2 including the cell colors and the border.

Also notice that all other rows in the existing dataset were simply pushed down.

Additional Resources

The following tutorials explain how to perform other common tasks in VBA:

VBA: How to Find Last Used Row
VBA: How to Count Number of Rows in Range
VBA: How to Count Number of Used Columns

Featured Posts

Leave a Reply

Your email address will not be published. Required fields are marked *