每隔一行添加行的宏

问题描述 投票:0回答:4

我的 Excel 电子表格上运行以下宏:

Sub yTest01()
    For i = 10 To 72 Step 2
        Cells(i, 1).EntireRow.Insert
    Next i
End Sub

它每隔一行添加一个新行。但是,我想每行添加五行。我尝试了以下方法,但不起作用

Sub yTest01()
    For i = 10 To 72 Step 2
        Cells(i, 1).EntireRow.Insert
        Cells(i, 1).EntireRow.Insert
        Cells(i, 1).EntireRow.Insert
        Cells(i, 1).EntireRow.Insert
        Cells(i, 1).EntireRow.Insert
    Next i
End Sub

有什么想法我可以做什么吗?

excel vba
4个回答
2
投票

我的猜测是,您需要一行现有数据,然后 5 行空白。尝试以下方法

Sub yTest01()
For i = 72 To 10 Step -1
    Cells(i, 1).EntireRow.Insert
    Cells(i, 1).EntireRow.Insert
    Cells(i, 1).EntireRow.Insert
    Cells(i, 1).EntireRow.Insert
    Cells(i, 1).EntireRow.Insert
Next i
End Sub

如果你想要的是两行数据然后五个空行然后将步骤更改为-2

添加或减去行时,最佳做法是向后循环。


2
投票

作为最佳实践,我努力减少 VBA 必须跨边界与 Excel 通信的次数。

因此,与其为每次插入跨越边界进行五次调用,不如进行一次调用。退后一步可能会有所帮助,但没有必要。

For i = 0 To 62 * 6 Step 6
    [10:10].Resize(5).Offset(i).Insert
Next

注意:迭代值 0 和 62 只是 OP 的行号调整为从零开始。


0
投票

为什么它不起作用?为什么要使用步骤 2? 移动行后可以移动 5 个位置吗?

Sub yTest01()
Dim i As Integer
    For i = 10 To 72 Step 1
        Cells(i, 1).EntireRow.Insert
        Cells(i, 1).EntireRow.Insert
        Cells(i, 1).EntireRow.Insert
        Cells(i, 1).EntireRow.Insert
        Cells(i, 1).EntireRow.Insert
        i = i + 5
    Next i
End Sub

0
投票

@ScottCraner @ExcelHero 我需要在 343 行现有数据的每一行之间添加 492 行空行。有人可以帮我做一下VBA吗?非常感谢。

© www.soinside.com 2019 - 2024. All rights reserved.