首页 > 解决方案 > 我的“更干净”代码运行速度比宏录制版本慢

问题描述

我在使用具有大量计算并且还必须运行一些目标搜索的电子表格时遇到了一个奇怪的问题。

这不是我的电子表格——它属于另一个团队——但我必须经常使用它,而且速度很慢。慢到让人讨厌。所以我试图加快速度,然后我会让其他团队切换到我更快的代码。

问题是,我重写的代码运行速度是原始宏记录代码的两倍,我不知道为什么。

原代码:

Range("P43").Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Copy
Range("P35").Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlSubtract, _
    SkipBlanks:=False, Transpose:=False
    Range("P43").GoalSeek Goal:=0, ChangingCell:=Range("P35")

Range("Q43").Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Copy
Range("Q35").Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlSubtract, _
    SkipBlanks:=False, Transpose:=False
Range("Q43").GoalSeek Goal:=0, ChangingCell:=Range("Q35")

...

它为每一列重复这个代码块,直到它到达 Z 列,所以它很长。

当我看到这个时,我认为加速它会很容易——摆脱选择、添加循环、关闭屏幕更新等——通常。

这是我重写的代码:

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

'our worksheet
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Analysis")

'column nos start with c; row nos with r
Dim cFirst As Integer, cLast As Integer, cCurrent As Integer
Dim rGoal As Integer, rChange As Integer

cFirst = 16 'col P
cLast = 26 'col Z

rGoal = 43
rChange = 35

With ws
    For cCurrent = cFirst To cLast
        'copy values from current column to last column to the other row
        .Range(.Cells(rChange, cCurrent), .Cells(rChange, cLast)).Value = .Range(.Cells(rGoal, cCurrent), .Cells(rGoal, cLast)).Value
        'run the goal seek on the current column
        .Cells(rGoal, cCurrent).GoalSeek Goal:=0, ChangingCell:=.Cells(rChange, cCurrent)
    Next cCurrent
End With

Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic

我做了什么明显错误的事情吗?我只是看不到它。我的新代码要短得多,并且产生完全相同的结果,但需要双倍的时间......

任何帮助将不胜感激!

标签: vbaexcelexcel-2010

解决方案


正如MacroMarc 敏锐地指出的那样,我并没有完全复制原始记录的代码——不敢相信我看不到它!

Selection.PasteSpecial Paste:=xlPasteValues, *>>*Operation:=xlSubtract*<<*, _
   ...

如果没有这个操作,重构的代码会引入一个错误,使GoalSeek调用工作比预期的要困难得多。赋值应该实现这个xlSubtract操作:

.Range(.Cells(rChange, cCurrent), .Cells(rChange, cLast)) _
.Value = .Range(.Cells(rChange, cCurrent), .Cells(rChange, cLast)).Value _
       - .Range(.Cells(rGoal, cCurrent), .Cells(rGoal, cLast)).Value

推荐阅读