VBA to insert row in named range keeping formatting and formulas

matthiasarnbert

New Member
Joined
Oct 3, 2022
Messages
2
Office Version
  1. 2019
Platform
  1. Windows
Hi. I'm trying to create a button that will insert a new row on the second row of a named range. I would like this new row to keep the same formatting and formulas as the row below it. The below code works well in terms of adding the new row on the second row of the named range. However, what do I need to add to also keep the formulas and formatting from the row below it? Any advice is appreciated!

Private Sub CommandButton1_Click()
Dim oRange As Range
Dim iColumns As Integer
Dim iRow As Integer

'Use Object variables to make code more legible
Set oRange = Worksheets("Sheet1").Range("Meals")
'Get Columns Width of named range
iColumns = oRange.Columns.Count
'Target the second row of the named range
iRow = 2

Set oRange = Range(oRange.Cells(iRow, 1), oRange.Cells(iRow, iColumns))
oRange.Insert Shift:=xlDown

End Sub
 

Excel Facts

Did you know Excel offers Filter by Selection?
Add the AutoFilter icon to the Quick Access Toolbar. Select a cell containing Apple, click AutoFilter, and you will get all rows with Apple
Like this: Copy/paste may keep source format and formula

VBA Code:
Private Sub CommandButton1_Click()
Dim r As Range
With Range("Meals").Rows(2)
    .Copy
    .Offset(1, 0).Insert Shift:=xlDown
    .Offset(1, 0).SpecialCells(xlCellTypeConstants).ClearContents ' remove cells without formula. obmit this line if want to keep the hardcode value
End With
End Sub
 
Upvote 0
Hi. Thanks for your repsonse. The code works great except it inserts the new row below the row that is being copied. Is there a way to get the new row to insert above the row being copied instead? Thanks.
 
Upvote 0

Forum statistics

Threads
1,215,748
Messages
6,126,654
Members
449,326
Latest member
asp123

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top