Results 1 to 3 of 3

Thread: Copy & insert the currently selected row of data multiple times

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    VBAX Newbie
    Joined
    Jun 2024
    Posts
    1
    Location

    Copy & insert the currently selected row of data multiple times

    Hello new to VBA here and spent a great deal trying to search and figure this out myself but cannot.


    I want to create a macro in excel that copies the currently active cells row and inserts it a number of times below by the currently selected cell and then changes whatever the number was to a 1. I have attached a before and after example below of what I am after.

    Before Macro.jpg After Macro.jpg

    I managed to find a code on this site which I changed slightly which can do the first part of my problem but not the second part of changing the specified number to a 1.

    Sub DuplicateRow()
        Dim NextRow As Long
        Dim NrOfCopies As Long
        Dim i As Long
        ' Dont think I need this? '
        Const NrOfCopiesDefault = 1
        Const NrOfCopiesMaximum = 1000
         
        Do
        ' I believe this selects the cell to start at and the number of copies to make '
            On Error Resume Next
            NrOfCopies = ActiveCell - 1
            On Error GoTo 0
            ' Dont think I need this'
            If NrOfCopies = 0 Then
                MsgBox "No copies made.", vbInformation, "CANCELLED"
                Exit Sub
            End If         
        Loop While NrOfCopies < 1 Or NrOfCopies > NrOfCopiesMaximum
        ' I assume this is the code to insert new rows and copy said row down a number of times '
        With Selection
            NextRow = .Row + .Rows.Count
            Rows(NextRow & ":" & NextRow + .Rows.Count * (NrOfCopies) - 1).Insert Shift:=xlDown
            .EntireRow.Copy Rows(NextRow & ":" & NextRow + .Rows.Count * (NrOfCopies) - 1)
            .Resize(.Rows.Count * (NrOfCopies + 1)).Sort key1:=.Cells(1, 1)
        End With
        ' I want to put in code to change the number in each copied row to a 1 here? '
    End Sub
    I'd me more than ok to edit the code above or start fresh. Also would love to add descriptive titles like in my code so I can understand what the code means for future reference as I love to learn new things. Thank you for your help.
    Last edited by Aussiebear; 05-04-2025 at 12:12 AM.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •