excel – 我的’清洁’代码比宏录制版本运行得慢

我遇到一个奇怪的问题,电子表格有大量的计算,还必须运行一些目标寻求.

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

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

原始代码:

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

我做过一些明显错误的事吗?我只是看不到它.我的新代码更短,产生完全相同的结果,但需要两倍的时间……

任何帮助将不胜感激!

最佳答案 作为
MacroMarc astutely pointed out,我没有完全复制原始录制的代码 – 不敢相信我看不到它!

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
点赞