简体   繁体   中英

Copy/Paste X number of times based on a cell value

I would like to copy a entire row and paste the values into another worksheet.

Ie

  1. Row 1 would be headers
  2. Row 2 would contain data to be copied
  3. Row 3 Same as row 2 above
  4. Repeated down.

Within the row of data there would be a cell in column M that would contain a number this number can change for each row so this would change the paste times.

I would like to copy & paste the full data in row, say 2, by the number in displayed in M2. If M2 has 4 then row 2 from sheet1 gets copied to sheet 2 four times one below the other.

Sheet 1 has 16 columns of data as shown below

Aa Bb Cc Dd Ee Ff Gg Hh Ii Gg Kk Ll **4** Nn Oo Pp

When macro is run it would look like this in Sheet2

Aa Bb Cc Dd Ee Ff Gg Hh Ii Gg Kk Ll **4** Nn Oo Pp<br>
Aa Bb Cc Dd Ee Ff Gg Hh Ii Gg Kk Ll **4** Nn Oo Pp<br>
Aa Bb Cc Dd Ee Ff Gg Hh Ii Gg Kk Ll **4** Nn Oo Pp<br>
Aa Bb Cc Dd Ee Ff Gg Hh Ii Gg Kk Ll **4** Nn Oo Pp<br>

This is what I have

Sub CopyRowsXTimes()
    Dim rngCell As Range

    ThisWorkbook.Worksheets("Sheet2").Cells.ClearContents
    For Each rngCell In ThisWorkbook.Worksheets("Sheet1").Range("N2:N" & _
    Cells(Rows.Count, 14).End(xlUp).Row)
        With ThisWorkbook.Worksheets("Sheet2")
            .Cells(.UsedRange.SpecialCells(xlCellTypeLastCell).Row + 1, _
            1).Resize(rngCell.Value, 5).Value = rngCell.Offset(, -3).Resize(1, 5).Value
        End With
    Next rngCell

    Set rngCell = Nothing
End Sub

The only problem with this that it only copies the 1st 4 columns. But I want the entire rows copied. At the moment there are 16 columns but it could grow in future.

It's pretty simple actually. Try this ( UNTESTED )

Sub Sample()
    Dim wsI As Worksheet, wsO As Worksheet
    Dim lRow_I As Long, lRow_O As Long, i As Long, j As Long

    '~~> Set your input and output sheets
    Set wsI = ThisWorkbook.Sheets("Sheet1")
    Set wsO = ThisWorkbook.Sheets("Sheet2")

    '~~> Output row
    lRow_O = wsO.Range("A" & wsO.Rows.Count).End(xlUp).Row + 1

    With wsI
        '~~> Get last row of input sheet
        lRow_I = .Range("A" & .Rows.Count).End(xlUp).Row

        '~~> Loop through the rows
        For i = 2 To lRow_I
            '~~> This will loop the number of time required
            '~~> i.e the number present in cell M
            For j = 1 To Val(Trim(.Range("M" & i).Value))
                '~~> This copies
                .Rows(i).Copy wsO.Rows(lRow_O)
                '~~> Get the next output row
                lRow_O = wsO.Range("A" & wsO.Rows.Count).End(xlUp).Row + 1
            Next j
        Next i
    End With
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM