复制并粘贴特定次数

时间:2016-09-05 17:20:21

标签: excel-vba vba excel

我有一列数据(F)和一列数字(G),我想要复制F列的每一行并粘贴到H列多次,这取决于列中的相应值G。 我怎么能用vba做到这一点?

  For exemple:      
          F          G        H
  4     Q7-CA        1      Q7-CA
  5     Q5-CA        2      Q5-CA
  6     A1-CA        1      Q5-CA
  7     Q6-CA        4      A1-CA
  8  BULK-TACEHU     1      Q6-CA
  9    AMA-EG        2      Q6-CA
 10                         Q6-CA
 11                         Q6-CA
 12                       BULK-TACEHU
 13                         AMA-EG
 14                         AMA-EG

1 个答案:

答案 0 :(得分:0)

使用下面的代码,我使用第1行作为数据开始的行(根据您的需要进行修改):

Option Explicit

Sub CopyNumofTimes()

Dim LastRow     As Long
Dim Sht         As Worksheet
Dim lRow        As Long
Dim newRow      As Long
Dim CopyRep     As Integer
Dim cpyRow      As Integer

' modify Sheet1 to your Sheet name
Set Sht = ThisWorkbook.Sheets("Sheet1")

' modify 1 form the line number you are starting your data
newRow = 1

With Sht
    ' find last row with data in Column F
    LastRow = .Cells(.Rows.Count, "F").End(xlUp).Row

    For lRow = 1 To LastRow
        CopyRep = .Cells(lRow, "G").Value

        ' make sure you have a number of at least 1 in Column G
        If CopyRep > 0 Then
            For cpyRow = 1 To CopyRep
                .Cells(newRow, "H") = .Cells(lRow, "F")
                newRow = newRow + 1
            Next cpyRow
        End If

    Next lRow

End With

End Sub