提高VBA的循环效率

时间:2017-06-15 11:59:41

标签: excel performance excel-vba for-loop vba

我有一个For循环,循环遍历整数1到9,只是找到对应于该整数的最底部条目(即1,1,1,2,3,4,5会找到第3个“1”条目)并插入一个空行。我将数字与字符串“FN”连接起来,该字符串只对应于此代码的应用程序,只是为了澄清。无论如何,它运行良好,但它只需要运行9个整数就相当多了。我希望有人能够帮助我调试以提高此代码的速度。谢谢! 如果任何人都可以通过一个很好的方式来填充插入的空白行,并使用跨越页面标题的格式化副本(“A1:L1”)。我尝试的代码在Next i之前被注释掉了。

Sub test()

Dim i As Integer, Line As String, Cards As Range
Dim Head As Range, LR2 As Long


        For i = 1 To 9
    Line = "FN" & CStr(i)
    Set Cards = Sheets(1).Cells.Find(Line, after:=Cells(1, 1), searchdirection:=xlPrevious)

    Cards.Rows.Offset(1).EntireRow.Insert
    Cards.Offset(1).EntireRow.Select
'    Range("A" & (ActiveCell.Row), "K" & (ActiveCell.Row)) = Range("A3:K3")
'    Range("A" & (ActiveCell.Row), "K" & (ActiveCell.Row)).Font.Background = Range("A3:K3").Font.Background

     Next i


End Sub

2 个答案:

答案 0 :(得分:6)

这对我来说非常快

Sub Sample()
    Dim i As Long, line As String, Cards As Range

    With Sheets(1)
        For i = 1 To 9
            line = "FN" & i

            Set Cards = .Columns(6).Find(line, LookIn:=xlValues, lookat:=xlWhole)

            If Not Cards Is Nothing Then
                .Range("A3:K3").Copy
                Cards.Offset(1, -5).Insert Shift:=xlDown
            End If
         Next i
    End With
End Sub

<强>之前

enter image description here

<强>后 enter image description here

答案 1 :(得分:0)

您的大多数改进都来自使用appTGGL帮助函数更改应用程序环境变量,但这里的基本代码中有一些调整。

Option Explicit

Sub ewrety()
    Dim f As Long, fn0 As String, fndfn As Range

    'appTGGL btggl:=false   'uncomment this when you are confident in it

    With Worksheets(1).Columns("F")
        For f = 1 To 9
            fn0 = Format$(f, "\F\N0")
            Set fndfn = .Find(What:=fn0, After:=.Cells(1), LookIn:=xlFormulas, LookAt:=xlWhole, _
                              SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False)
            With fndfn
                .Offset(1, -5).EntireRow.Insert Shift:=xlDown
                .Parent.Range("A1:L1, XFC1").Copy Destination:=.Offset(1, -5)
            End With
        Next f
    End With

    appTGGL
End Sub

Public Sub appTGGL(Optional bTGGL As Boolean = True)
    With Application
        .ScreenUpdating = bTGGL
        .EnableEvents = bTGGL
        .DisplayAlerts = bTGGL
        .AutoRecover.Enabled = bTGGL   'no interruptions with an auto-save
        .Calculation = IIf(bTGGL, xlCalculationAutomatic, xlCalculationManual)
        .CutCopyMode = False
        .StatusBar = vbNullString
    End With
    Debug.Print Timer
End Sub

enter image description here