【问题标题】:VBA Excel - insert copied rows in For loopVBA Excel - 在 For 循环中插入复制的行
【发布时间】:2017-08-08 23:58:19
【问题描述】:

我正在通过一组行执行 For Each 循环。我将这些行复制了一组不同的时间。例如,第 2 行将被复制 3 次,但第 3 行不会被复制,第 4 行将被复制 2 次。

此复制行数由 excel 中的字段设置 - totalDS

问题是,当我插入这段代码时

Set RowRange = sh.Range("A2:A" & LastRow)

For Each rowiter In RowRange

    Dim i As Integer

    For i = 2 To totalDS

        With Worksheets("Sheet1")
            .Rows(rowiter.Row).Copy
            .Rows(rowiter.Row).Offset(1).Insert Shift:=xlDown
            Application.CutCopyMode = False
        End With

    Next i

Next rowiter

我将在我复制的那个旁边有一排,这是正确的。但我需要我的 For 循环的下一步转到下一个未复制的行。就像现在一样,For 循环只会转到下一行,所以它会一遍又一遍地复制同一行。

有什么建议吗?

【问题讨论】:

  • 据我所知,这不适用于 for/each 循环。你的方法的目的是什么?您是否希望 Range 中的每一行都重复 x 次?

标签: excel for-loop foreach vba


【解决方案1】:

我刚刚做了这个示例测试子来展示它是如何工作的。此子从行 i=2 到行 LastRow=10 并复制每一行 totalDS=2 次。

Sub test()
    Dim sh As Worksheet
    Set sh = Worksheets("Sheet1")

    Dim LastRow As Long
    LastRow = 10

    Dim totalDS As Long
    totalDS = 2


    Dim i As Long, j As Long

    i = 2 'we start at row i
    Do While i <= LastRow 'and we end at LastRow

        For j = 1 To totalDS 'insert row totalDs times
            sh.Rows(i).Copy 'copy row
            sh.Rows(i).Offset(1).Insert Shift:=xlDown
        Next j

        i = i + totalDS + 1 
           'We need to go totalDs rows forward (because we inserted
           'totalDS rows) + 1 row further to get the next new row.

        LastRow = LastRow + totalDS
           'We also need to increase LastRow by totalDS because we
           'inserted totalDS rows and LastRow also moved totalDS rows down.
    Loop

    Application.CutCopyMode = False 'it's enough to use this at the very last end
End Sub

【讨论】:

    【解决方案2】:

    当您插入一行时,尝试将索引增加 1。例如 i = i + 1

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-13
      相关资源
      最近更新 更多