VBA代码运行时间太长

时间:2018-08-29 12:12:16

标签: vba excel-vba

请参阅下面提供的以下VBA代码。本质上,这是要打开另一个工作簿,取消合并行,复制列并将其粘贴到我的活动工作簿中。但是,复制粘贴后,当代码运行到CalculationAutomatic行时,大约需要15分钟。还有其他方法可以提高效率吗? 谢谢

for item in list(NoDot1x):
 if "Interface Vlan" in item:
  somelist.remove(item)

1 个答案:

答案 0 :(得分:1)

对于初学者来说,可能如下所示。理想情况下,优化步骤将放在自己的子目录中。一个在开始时打开优化,另一个将所有内容返回到结束时的状态(或出现错误时)。

根据要求,这将向您展示如何使用With语句删除代码中的.Select部分。它还包含一个安全出口,以防万一出现错误,可以重新启用您禁用的所有功能。

Option Explicit
Public Sub ImportRemarks()
    Dim PLPath As String, wbThis As Workbook, wbTarget As Workbook

    Application.Calculation = xlCalculationManual
    Application.ScreenUpdating = False
    Application.EnableEvents = False

    On Error GoTo Errhand
    Set wbThis = ThisWorkbook
    Set wbTarget = Workbooks.Open(PLPath)
    PLPath = wbThis.Worksheets("Instructions").Range("C16").Text

    wbTarget.Worksheets("Performance List").Rows("1:2").UnMerge

    With wbThis.Worksheets("keys")
        .Range("I:I") = wbTarget.Worksheets("Performance List").Range("F:F")
        .Range("J:L") = wbTarget.Worksheets("Performance List").Range("P:R")
    End With

    wbTarget.Close savechanges:=False

    With wbThis
        .Activate
        ' .Worksheets("Instructions").Range("C22").Activate '<=consider whether this is needed?
    End With

Errhand:
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True
    Application.EnableEvents = True
End Sub

更多有关优化的信息:

https://www.thespreadsheetguru.com/blog/2015/2/25/best-way-to-improve-vba-macro-performance-and-prevent-slow-code-execution

http://www.cpearson.com/excel/optimize.htm