需要修改代码以添加10空行

时间:2019-02-15 14:56:16

标签: excel vba

我需要这段代码来添加10行而不是1行。

我对VBA知之甚少,但是从另一个站点偷走了这段代码,这几乎正是我所需要的。它在“错误:”下面插入一行,但是我真的需要它来插入10条空行。

Sub BlankLine()
    'Updateby20150203
    Dim Rng As Range
    Dim WorkRng As Range
    On Error Resume Next
    xTitleId = "KutoolsforExcel"
    Set WorkRng = Application.Selection
    Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)
    Set WorkRng = WorkRng.Columns(1)
    xLastRow = WorkRng.Rows.Count
    Application.ScreenUpdating = False
    For xRowIndex = xLastRow To 1 Step -1
        Set Rng = WorkRng.Range("A" & xRowIndex)
        If Rng.Value = "ERROR:" Then
            Rng.Offset(1, 0).EntireRow.Insert Shift:=xlDown
        End If
    Next
    Application.ScreenUpdating = True
End Sub

实际结果是增加了1行,但我希望有10条空行。

2 个答案:

答案 0 :(得分:1)

尽管Raul Guerrero建议的解决方案可行,但它有一个缺点:插入行/列的速度很慢,因此与其一次插入10行,不如一次插入全部行,要好得多。

Scott Craner(在评论中)的解决方案应该更快,但我认为他有错字。我认为应该是

rng.Offset(1, 0).Resize(10, 1).EntireRow.Insert

答案 1 :(得分:0)

我刚刚对您的代码做了一些修改... 我希望这能如您所愿!

您能尝试一下吗?

Sub BlankLine()
    'Updateby20150203
    Dim Rng As Range
    Dim WorkRng As Range
    On Error Resume Next
    xTitleId = "KutoolsforExcel"
    Set WorkRng = Application.Selection
    Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)
    Set WorkRng = WorkRng.Columns(1)
    xLastRow = WorkRng.Rows.Count
    Application.ScreenUpdating = False
    For xRowIndex = xLastRow To 1 Step -1
        Set Rng = WorkRng.Range("A" & xRowIndex)
        If Rng.Value = "ERROR:" Then
            For i = 1 To 10
                Rng.Offset(1, 0).EntireRow.Insert Shift:=xlDown
            Next
        End If
    Next
    Application.ScreenUpdating = True
End Sub