根据单元格值复制行X的次数

时间:2016-02-25 11:01:38

标签: excel vba excel-vba

宏根据M2中的单元格值复制并粘贴行X的值。它会反复粘贴确切的数字。有没有办法改变它,以便数字在复制时会提升?

E.g。如果A2包含"你好3",在运行宏A3之后将包含" hello 4",A4将包含"你好5"

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("Sheet1")

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

输入屏幕和输出屏幕的外观示例:

Input

输出屏幕的外观示例:

Output

2 个答案:

答案 0 :(得分:0)

如果使用resize方法,实际上不需要j循环。

Sub Sample()
Dim wsI As Worksheet, wsO As Worksheet, lCounter As Long
Dim lRow_I As Long, lRow_O As Long, i As Long

Set wsI = ThisWorkbook.Sheets("Sheet1")
Set wsO = ThisWorkbook.Sheets("Sheet2")

With wsI
    lCounter = Val(Trim(.Range("M" & i).Value))
    lRow_I = .Range("A" & .Rows.Count).End(xlUp).Row

    For i = 2 To lRow_I
        lRow_O = wsO.Range("A" & wsO.Rows.Count).End(xlUp).Row + 1
        .Rows(i).Copy wsO.Rows(lRow_O).Resize(lCounter)
    Next i

End With

答案 1 :(得分:0)

我升级我的解决方案以获得"计数器"递增

GetPropertyValue

它不需要内部j循环,只需升级lRow_O