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
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