Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a new row into a range and copy formulas

Tags:

excel

vba

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.

like image 494
Samuel Goldenbaum Avatar asked Apr 11 '10 07:04

Samuel Goldenbaum


People also ask

How do you copy formulas from one row to another?

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


1 Answers

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
like image 130
marg Avatar answered Nov 09 '22 15:11

marg