I have a named range like the following covering A2:D3
ITEM PRICE QTY SUBTOTAL
1 10 3 30
1 5 2 10
TOTAL: 40
I am to insert a new row using VBA into the range copying the formulas not values.
Any tips/links greatly appreciated.
The one thing to watch for is that the cell references used in the formula are still what you want after you move. Select the cell that contains the formula you want to move. Click Home > Cut (or press Ctrl + X). Select the cell you want the formula to be in, and then click Paste (or press Ctrl + V).
This should do it:
Private Sub newRow(Optional line As Integer = -1)
Dim target As Range
Dim cell As Range
Dim rowNr As Integer
Set target = Range("A2:D3")
If line <> -1 Then
rowNr = line
Else
rowNr = target.Rows.Count
End If
target.Rows(rowNr + 1).Insert
target.Rows(rowNr).Copy target.Rows(rowNr + 1)
For Each cell In target.Rows(rowNr + 1).Cells
If Left(cell.Formula, 1) <> "=" Then cell.Clear
Next cell
End Sub
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With