提高VBA的循环效率

我有一个For循环,通过整数1到9循环,只是find对应于该整数(即1,1,1,2,3,4,5将find第三个“1”条目)最底部的条目,并插入一排空白。 我将这个数字和一个string“FN”连接起来,这个string恰好与这个代码的应用程序相对应。 无论如何,它运作良好,但它只有贯穿9个整数才有点滞后。 我希望有人能够帮助我debugging,以提高这个代码的速度。 谢谢! 如果有人可以通过一个很好的方式来填充插入的空白行,使用横跨(“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 

这对我来说工作得相当快

 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 

之前

在这里输入图像描述

在这里输入图像描述

你的大部分改进都来自于使用appTGGL helper函数改变应用程序环境variables,但是这里的基本代码有一些调整。

 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 

在这里输入图像说明