使用`With`而不是`.Select`插入新行

时间:2017-01-20 13:54:07

标签: excel vba select insert

在编写插入新行的代码时,我在尝试使用with而不是.select时遇到问题。有人多次告诉我.select不会被使用,因为速度要慢得多。

我的宏创建了一个新行,但是删除了下面行中的内容,并复制了我在使用.select时从未发生过的行的格式。这也意味着单元格B11中的数字增加不正确,因为它由于下面清除的内容而从1再次开始。

Sub New_Entry()

Application.ScreenUpdating = False
Application.EnableEvents = False

Dim rng As Range
Set rng = Range("B11:AB11")

With rng
.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
End With
Application.CutCopyMode = False

With rng
.ClearContents
.Interior.ColorIndex = xlNone
.Borders.LineStyle = xlContinuous
End With

With Range("B11")
    .Value = Range("B12") + 1
End With

With rng
    .Font.Bold = False
    .Font.ColorIndex = xlAutomatic
    .Font.TintAndShade = 0
End With

Application.EnableEvents = True
Application.ScreenUpdating = True

End Sub

任何帮助将不胜感激,谢谢!

2 个答案:

答案 0 :(得分:2)

据我所知,你有两个问题:

<强> 1。为什么会删除内容?

这是因为您的With rng在插入一行的同时接受Set rng = Range("B11:AB11").ClearContents <。>

您可以通过切换代码的​​顺序来检查这一点。 具有相同条件的所有With语句始终同时运行。

<强> 2。为什么要复制格式?

实际上并未复制格式,而是使用.Borders.LineStyle = xlContinuous格式化您创建的每一行。

这应该有效:

Sub New_Entry()

Application.ScreenUpdating = False
Application.EnableEvents = False

Dim rng As Range
Set rng = Range("B11:AB11")

With rng
'.ClearContents
.Interior.ColorIndex = xlNone
'.Borders.LineStyle = xlContinuous
'End With

'With rng
.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
End With
Application.CutCopyMode = False

With Range("B11")
    .Value = Range("B12") + 1
End With

With rng
    .Font.Bold = False
    .Font.ColorIndex = xlAutomatic
    .Font.TintAndShade = 0
End With

Application.EnableEvents = True
Application.ScreenUpdating = True

End Sub

.Select速度较慢,因为它逐行运行代码。

答案 1 :(得分:1)

插入后范围“rng”似乎向下移动。这是我要采取的路线:

Sub New_Entry()

    Application.ScreenUpdating = False
    Application.EnableEvents = False

    Range("B11:AB11").Insert Shift:=xlDown

    Range("B11").Value = Range("B12") + 1

    With Range("B11:AB11")
        .Interior.ColorIndex = xlNone
        .Borders.LineStyle = xlContinuous
        .Font.Bold = False
        .Font.ColorIndex = xlAutomatic
        .Font.TintAndShade = 0
    End With

    Application.EnableEvents = True
    Application.ScreenUpdating = True

End Sub