我有一大堆数据(假设它从B5到J500,让我们说这个范围被命名为rngOutput)。我正在尝试浏览此数据并在每个 x 行数中添加2个空行,其中x是用户指定的数字。例如,如果x为10,则应插入每10行2个新行。从概念上讲,这是应该工作的代码:
For i = 1 to Number of rows in rngOutput
If i mod x = 0 Then
Insert 2 Rows
End If
Next i
但是,当您插入2个新行时,行数会更改并且公式会混乱(即在前10行之后添加2行,然后在接下来的8行之后再添加2行(因为它会计算2行)您添加为实际行的新行)然后在接下来的6行之后再添加2行,等等。
我正试图找到一种方法来完成每x行数干净地添加2个新行以避免上述问题。
感谢您的帮助,如果您需要进一步说明,请与我们联系!
答案 0 :(得分:5)
这就像克里斯唯一的充实。插入或删除行时,您必须从底部开始处理:
Sub InsertXRowsEveryYRows_WithMeaningfulVariableNames()
Dim NumRowsToInsert As Long
Dim RowIncrement As Long
Dim ws As Excel.Worksheet
Dim LastRow As Long
Dim LastEvenlyDivisibleRow
Dim i As Long
NumRowsToInsert = 2 'any number greater than 0
RowIncrement = 10 'ditto
Set ws = ActiveSheet
With ws
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
LastEvenlyDivisibleRow = Int(LastRow / RowIncrement) * RowIncrement
If LastEvenlyDivisibleRow = 0 Then
Exit Sub
End If
Application.ScreenUpdating = False
For i = LastEvenlyDivisibleRow To 1 Step -RowIncrement
.Range(i & ":" & i + (NumRowsToInsert - 1)).Insert xlShiftDown
Next i
End With
Application.ScreenUpdating = True
End Sub
答案 1 :(得分:4)
从范围的底部算起
For i = Number of rows in rngOutput to 1 step -1
If i mod x = 0 Then
Insert 2 Rows
End If
Next i