Excel - A macro to copy rows X number of times

Ask a question



Macros can be used in Excel office software to copy rows for x number of times. Repetitive tasks such as copying data from rows manually become non-feasible if the number of records in an Excel worksheet is too high. Even for smaller worksheets, it is advisable to use macros for tasks such as copying rows for X number of times in a worksheet. Macros perform the task automatically with minimal human intervention reducing the chances of errors. Pre-written macros can be downloaded from various online resources and changed to perform the desired tasks. Some knowledge of programming may be required.

Issue


I'd like to take the first row in my spreadsheet, copy it "X" number of times, then take the next row, copy it the same "X" number of times, until the end of the rows.

Sample
ColA ColB ColC        
TextA TextA1 TextA2        
TextB TextB1 TextB2        
TextC TextC1 TextC2        

Results (for example 3 times)        
ColA ColB ColC        
TextA TextA1 TextA2        
TextA TextA1 TextA2        
TextA TextA1 TextA2        
TextB TextB1 TextB2        
TextB TextB1 TextB2        
TextB TextB1 TextB2        
TextC TextC1 TextC2        
TextC TextC1 TextC2        
TextC TextC1 TextC2 

Solution


This is the macro:

Sub test()       
Dim rng As Range, c As Range       
Dim rng1 As Range, c1 As Range       
Dim dest As Range, j As Integer, k As Integer       
Worksheets("sheet2").Cells.Clear       
With Worksheets("sheet1")       
Set rng = Range(.Range("A2"), .Range("A2").End(xlDown))       
j = WorksheetFunction.CountA(.Rows("1:1"))       
'msgbox j       
For Each c In rng       
Set rng1 = Range(c.Offset(0, 1), .Cells(c.Row, Columns.Count).End(xlToLeft))       
'msgbox rng1.Address       
For Each c1 In rng1       

Set dest = Worksheets("sheet2").Cells(Rows.Count, "a").End(xlUp).Offset(1, 0)       
'msgbox dest.Address       
If c1 = "" Then GoTo line1       
dest.Offset(0, 0) = c       
dest.Offset(0, 1) = .Cells(1, c1.Column)       
'dest.Offset(0, 2) = c1       
line1:       
Next c1       

Next c       
End With       
End Sub


Another method -pivot table of database.-
ref: wlakenbach blog

http://spreadsheetpage.com/...

Note


Thanks to venkat1926 for this tip on the forum.
Jean-François Pillou

CCM is a leading international tech website. Our content is written in collaboration with IT experts, under the direction of Jeff Pillou, founder of CCM.net. CCM reaches more than 50 million unique visitors per month and is available in 11 languages.

Learn more about the CCM team