根据单元格值向表中添加行

时间:2017-10-10 00:44:32

标签: excel vba excel-vba

我试图添加等于B列中值的空行     Sub AddRows()

Dim cell As Range, numberRange As Range
Dim i As Integer, j As Integer
Set numberRange = Range("B2:B5")

For Each cell In numberRange
    Set i = 1
    Set j = Int(cell.Value)
    For i = 1 To j
        cell.EntireRow.Insert xlDown
    Next i
Next cell

End Sub

例如,如果值2在B2中,我希望在第3行:第4行中添加两个空白行。

1 个答案:

答案 0 :(得分:0)

是的,PatricK是对的。您应该从范围的底部开始插入,以便新行不会陷入现有行的计数中。

Sub AddRows()

    Dim R As Long
    Dim i As Integer

    Application.ScreenUpdating = False
    For R = 5 To 2 Step -1
        With Cells(R, 2)
            i = int(Val(.Value))
            If i Then
                .Offset(1).Resize(i, 1).EntireRow.Insert
            End If
        End With
    Next R
    Application.ScreenUpdating = True
End Sub