每个循环的MS Excel:插入行

时间:2013-04-14 17:20:39

标签: excel-vba vba excel

我有一个包含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 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

3 个答案:

答案 0 :(得分:2)

也许这会有所帮助

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

答案 1 :(得分:2)

最简单的方法就是倒计时,比如

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

答案 2 :(得分:1)

如果您为每个循环 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