[英]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 即
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. 在数据行中, M
列中将有一个单元格,其中包含一个数字,该数字可以针对每一行更改,因此这将更改粘贴时间。
I would like to copy & paste the full data in row, say 2, by the number in displayed in M2. 我想按M2中显示的数字将完整数据复制并粘贴到第二行中。 If M2
has 4
then row 2 from sheet1 gets copied to sheet 2 four times one below the other. 如果M2
有4
则Sheet1的第2行被复制到工作表2上,四次一遍。
Sheet 1 has 16 columns of data as shown below 工作表1包含16列数据,如下所示
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 运行宏时,在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. 唯一的问题是它仅复制第1 4列。 But I want the entire rows copied. 但是我要复制整个行。 At the moment there are 16 columns but it could grow in future. 目前有16列,但将来可能会增加。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.