简体   繁体   中英

Copy and paste rows x times based if x=“cell value”

copy rows x-times and paste in new sheet x-amount of Rows. Then change the cell value of Col "S" to "1 of x", "2 of x", "3 of x"...."x of x".

"Sheet1" Col "S" holds the x-numerical value. Copy col "B" through "AJ" in each row with value and paste in "sheet3".

I have used some code found in stack overflow at " Copy Row X amount of times based on cell value ", but need it to change value of "S" in each added row.

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("Sheet3")

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

With wsI
    '~~> Get last row of input sheet
    lRow_I = .Range("B" & .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 S
        For j = 1 To Val(Trim(.Range("S" & i).Value))
            '~~> This copies
            .Rows(i).Copy wsO.Rows(lRow_O)
            '~~> Get the next output row
            lRow_O = wsO.Range("B" & wsO.Rows.Count).End(xlUp).Row + 1
        Next j
    Next i
End With
End Sub

I expect each row on sheet 1 to be on sheet 3 the amount of times cell "S" ("S"= numerical digit between 1-15) in that row's value is. Then each new line added will have "S" value "1 of S", "2 of S", and so on to "S of S".

Sub Sample()

    Dim wsI As Worksheet, wsO As Worksheet
    Dim lRow_I As Long, lRow_O As Long, i As Long, j As Long
    Dim rw As Range, n As Long

    Set wsI = ThisWorkbook.Sheets("Sheet1")
    Set wsO = ThisWorkbook.Sheets("Sheet3")

    lRow_O = wsO.Range("B" & wsO.Rows.Count).End(xlUp).Row + 1
    lRow_I = wsI.Range("B" & wsI.Rows.Count).End(xlUp).Row

    For i = 2 To lRow_I

        Set rw = wsI.Rows(i)
        n = Val(Trim(rw.Range("S1").Value))

        rw.Copy wsO.Rows(lRow_O).Resize(n) 'makes n copies of the row

        'add the "x of n" values
        wsO.Cells(lRow_O, "S").Resize(n, 1).Value = Evaluate("=ROW(1:" & n & ") & "" of " & n & """")

        'or alternatively / less complex...
        for j = 1 to n
            wsO.Cells(lRow_O, "S").Offset(j-1, 0).Value = j & " of " & n
        next j

        lRow_O = lRow_O + n

    Next i

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