我正在通过一组行进行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循环只会转到下一行,所以它会一遍又一遍地复制同一行。
有关此的任何提示吗?
答案 0 :(得分:1)
我刚刚做了这个示例test sub来展示它是如何工作的。该子行从行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
答案 1 :(得分:0)
插入行时,请尝试将索引递增1.例如i = i + 1