MS Excel For Each循环:插入行
我有一个包含242行的工作表。我想在每个现有行下面创建一个新行。相反,我的代码在第1行下面创建了242行。我花了整个下午的时间在Google和Stack Overflow上,尝试了各种想法,但都遇到了同样的问题。这是我的密码:MS Excel For Each循环:插入行,excel,vba,Excel,Vba,我有一个包含242行的工作表。我想在每个现有行下面创建一个新行。相反,我的代码在第1行下面创建了242行。我花了整个下午的时间在Google和Stack Overflow上,尝试了各种想法,但都遇到了同样的问题。这是我的密码: Function rws() As Integer rws = (Cells(Rows.Count, "A").End(xlUp).Offset(1, 0).row) End Function Sub InsRws() Dim rng As Range Dim r
Function rws() As Integer
rws = (Cells(Rows.Count, "A").End(xlUp).Offset(1, 0).row)
End Function
Sub InsRws()
Dim rng As Range
Dim row As Range
Set rng = Range("A1:A" & rws - 1)
For Each row In rng.Rows
Rows.Select
ActiveCell.Offset(1).EntireRow.Insert
Next row
End Sub
也许这会有帮助
Function rws() As Integer
rws = (Cells(rows.Count, "A").End(xlUp).Offset(1, 0).row)
End Function
Sub InsRws()
Dim rowCount As Integer
Dim i As Integer
rowCount = rws
For i = 1 To rowCount
Range("A" + CStr(2 * i - 1)).Select
ActiveCell.Offset(1).EntireRow.Insert
Next
End Sub
如果您为每个循环调试
debug.print row.address
,您会注意到当插入时,您的rng一直在扩展。相反,您可以使用for循环,如下代码所示
Sub InsRws()
Dim lastRow As Long
lastRow = Sheets("Sheet1").Range("A65000").End(xlUp).Row
For i = 1 To lastRow
Range("A" & i * 2).EntireRow.Insert
Next
End Sub
最简单的方法是倒计时,而不是倒计时,就像这样
Sub InsertRows()
Dim rw As Long
With ActiveSheet
For rw = .Cells(.Rows.Count, 1).End(xlUp).Row To 2 Step -1
.Rows(rw).Insert
Next
End With
End Sub
请选择一个最适合你的问题的帖子作为答案是的,如果其中一个提议的答案解决了你的问题,那么为了未来读者的利益,你应该“接受”它(并给花时间帮助你的人一些声誉分数)。