Forum Discussion

Celia9's avatar
Celia9
Brass Contributor
Jul 11, 2022
Solved

Add new row, copy from cell above

Hi,   I have a macro to add a new row, but now I want to paste the value from the above row.   My code:   Private Sub CommandButton1_Click() Dim rowNum As Integer On Error Resume Next rowNum...
  • HansVogelaar's avatar
    HansVogelaar
    Jul 11, 2022

    Celia9 

    How about this:

    Private Sub CommandButton1_Click()
        Dim tbl As ListObject
        Dim row1 As Long
        Dim row2 As Long
        Dim rowNum As Long
        rowNum = Application.InputBox(Prompt:="Enter Row Number where you want to add a row:", _
            Title:="Add row", Type:=1)
        Set tbl = Me.ListObjects(1)
        row1 = tbl.Range.Row
        row2 = row1 + tbl.Range.Rows.Count - 1
        If rowNum <= row1 + 1 Or rowNum > row2 + 1 Then
            MsgBox "Row number not valid for table! Please try again.", vbExclamation
        Else
            tbl.ListRows.Add Position:=rowNum - row1
            Cells(rowNum, 1).Value = Cells(rowNum - 1, 1).Value
        End If
    End Sub

Resources