我遇到了一个奇怪的问题,该电子表格包含大量计算,并且还必须运行一些目标搜索。
这不是我的电子表格 - 它属于另一个团队 - 但我必须经常使用它,而且速度很慢。慢到很烦人。所以我试图加快速度,然后我会让另一个团队切换到我更快的代码。
问题是,我重写的代码的运行速度是原始宏录制代码的两倍,我说不出原因。
原始代码:
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 敏锐地指出的那样,我并没有完全复制原始录制的代码 - 简直不敢相信我看不到它!
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