Excel - Repeat rows to a specific number of times

Solved/Closed
arhee Posts 2 Registration date Saturday February 8, 2014 Status Member Last seen February 10, 2014 - Feb 8, 2014 at 12:45 AM
daphtan Posts 2 Registration date Monday June 23, 2014 Status Member Last seen June 23, 2014 - Jun 23, 2014 at 05:48 AM
Hello,

Hi

Does anybody know how I can repeat rows in a spreadsheet (or into another spreadsheet) by n number of times specified in the cell in that row to another cell

ie from this table:

Column A Column B
Peter 3
James 7
David 4

I need to produce this table:
Column C Column D
Peter 1
Peter 2
Peter 3
James 1
James 2
James 3
James 4
James 5
James 6
James 7
David 1
David 2
David 3
David 4

Any ideas on a simple way of doing this?

Any help would be greatly appreciated.




2 replies

venkat1926 Posts 1864 Registration date Sunday June 14, 2009 Status Contributor Last seen August 7, 2021 810
Jun 23, 2014 at 03:44 AM
data is in sheet1

header 1 header 2 header 3
Peter male 3
james male 7
David male 4

try this macro and see sheet 2

Sub test()
Dim rA As Range, cA As Range, dest As Range, j As Long, k As Long
Dim nname As String, sex As String
'data is in sheet1
With Worksheets("sheet1")
Set rA = Range(.Range("A2"), .Range("A2").End(xlDown))
For Each cA In rA
j = .Cells(cA.Row, "C")
nname = cA
sex = .Cells(cA.Row, "B")
With Worksheets("sheet2")

For k = 1 To j
Set dest = .Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
dest = nname
dest.Offset(0, 1) = sex
dest.Offset(0, 2) = j & "." & k
Next k
End With
Next cA
End With


End Sub
0
daphtan Posts 2 Registration date Monday June 23, 2014 Status Member Last seen June 23, 2014
Jun 23, 2014 at 05:48 AM
thanks so much~~~ it works for me! saved me a lot of time!

but another query is, if I have multiple columns to be repeated based on the number in col x, do I change to something like this:

Sub test()
Dim rA As Range, cA As Range, dest As Range, j As Long, k As Long
Dim batch As String, location As String, code As String, color As String

'data is in sheet1
With Worksheets("sheet10")
Set rA = Range(.Range("A2"), .Range("A2").End(xlDown))
For Each cA In rA
j = .Cells(cA.Row, "E")
batch = cA
location = .Cells(cA.Row, "B")
code = .Cells(cA.Row, "C")
color = .Cells(cA.Row, "D")
With Worksheets("sheet11")

For k = 1 To j
Set dest = .Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
dest = batch
dest.Offset(0, 1) = location
dest.Offset(0, 2) = code
dest.Offset(0, 3) = color
dest.Offset(0, 4) = j & "." & k
Next k
End With
Next cA
End With


End Sub
0