在原始位置插入复制的行

时间:2016-02-09 06:59:29

标签: vba copy rows paste

我有一个用户输入整数的单元格,在本例中为D4。然后,我想复制特定数量的行,并将它们粘贴在原始单元格下方,用户输入所指示的次数。

我的代码卡在循环中,它只是连续插入单元格,最终Excel崩溃,因为我达到了最大行数。我正在尝试复制4行并将它们分别粘贴2次。

以下是代码的副本。

Sub Worksheet_Change(ByVal Target As Range)
    If (Range("D4") <= 1) Then
    End If
    If (Range("D4") > 1) Then
        Dim I As Integer
        Dim SR As Integer
        Dim K As Integer
        Dim NR As Integer
        SR = 6 'starting row
        ER = 4 'number of rows after starting row aka ending row
        NR = 5 'number of rows to inbetween paste operation and original
        For K = 1 To Range("D4") Step 1
            For I = SR To SR + ER Step 1
                Rows(I + NR).EntireRow.Insert
                Rows(I).Copy
                Rows(I + NR).PasteSpecial
            Next I
        Next K
    End If
End Sub

1 个答案:

答案 0 :(得分:1)

我在您的代码中看到了一些问题,因此我对其进行了重新组织和编辑:

Sub Worksheet_Change(ByVal Target As Range)

    Dim WS As Worksheet
    Set WS = ActiveWorkbook.Sheets("Sheet2")

    Dim CellValue As Integer
    CellValue = WS.Range("D4").Value

    If (CellValue <= 1) Then
        MsgBox "Your value is too small. Please enter a new value.", vbOkOnly
        'Exit Sub would also work if you'd want that.
    End If

    If (CellValue > 1) Then
        Dim I As Integer
        Dim SR As Integer
        Dim K As Integer
        Dim NR As Integer
        SR = 6
        ER = SR + 4
        NR = 5
        For K = 1 To CellValue
            For I = SR To ER
                WS.Rows(I).Copy
                WS.Rows(I + NR).EntireRow.Insert
                WS.Rows(I + NR).PasteSpecial
            Next I
        Next K
    End If
End Sub

要知道,每当该工作表(Worksheet_CHANGE)发生任何变化时,都会运行此代码。这也意味着每次插入一行时它将重新运行sub。如果你在D4旁边放一个可以调用那个子的按钮可能会更好。