4

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

3 回答 3

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
于 2013-04-14T18:24:59.790 回答
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
于 2013-04-14T20:31:50.833 回答
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
于 2013-04-14T18:34:50.913 回答