[英]How can I optimize a VBA module that requires many calls to a subroutine?
I am writing code for an Excel workbook provided by a client.我正在为客户提供的 Excel 工作簿编写代码。
The purpose of this macro is to load the data for a customer into a sheet.该宏的目的是将客户的数据加载到工作表中。 When it does, the listener on one of the loaded cells is triggered, and it calls the appropriate subroutine associated with that customer's information.当它这样做时,将触发其中一个已加载单元格上的侦听器,并调用与该客户信息关联的适当子例程。
The code is operating exactly as expected and completes in a few seconds.该代码完全按预期运行,并在几秒钟内完成。 However, the client wishes us to perform this task on roughly 15,000 customers in sequence.但是,客户希望我们按顺序对大约 15,000 名客户执行此任务。
When we attempt to iterate the macro over roughly a hundred customers, the macro completes in a matter of a few minutes.当我们尝试对大约一百个客户迭代宏时,宏会在几分钟内完成。 However, when we increase the number of customers to around a thousand, the time to complete the run increases drastically.然而,当我们将客户数量增加到大约一千时,完成运行的时间会急剧增加。
I've been trying for days to optimize the subroutine itself, but the slowdown only arises when we are calling the subroutine upwards of a thousand times.几天来我一直在尝试优化子例程本身,但只有当我们调用子例程超过一千次时才会出现减速。
Why would repeated calls to the subroutine cause slowdown in the execution of the code, and is there a way that it can be mitigated?为什么重复调用子例程会导致代码执行速度变慢,有没有办法可以缓解这种情况?
Sub Looprun()
Dim n As Long
Dim lastRow As Long
Dim SecondLastrow As Long
Dim Start As Long
Dim Finish As Long
Application.Calculation = xlManual
Application.ScreenUpdating = False
'Set starting timestamp
Range("RunStart").Value = Now()
Start = Sheets("Reserve Summary").Range("L12").Value
Finish = Sheets("Reserve Summary").Range("L13").Value
lastRow = Cells(Sheets("Reserve Summary").Rows.Count, 2).End(xlUp).Row - 1
For n = Start To Finish
Sheets("Calculation").Cells(3, 3).Value = n
' Cell C3 has a listener attached to it; see below. The customer's other information is loaded in via formulas that are keyed to cell C3.
Sheets("Reserve Summary").Cells(n + 2, 3).Value = Sheets("Calculation").Range("C4").Value
Sheets("Reserve Summary").Cells(n + 2, 5).Value = Sheets("Calculation").Range("Q25").Value
Sheets("Reserve Summary").Cells(n + 2, 7).Value = Sheets("Calculation").Range("Q22").Value
Next
Range("RunEnd").Value = Now()
Application.Calculation = xlAutomatic
Application.Calculate
Application.ScreenUpdating = True
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
Dim company As String
If Target.Address = "$C$3" Then
Worksheets("Calculation").Calculate
company = Sheets("Calculation").Cells(3, 11).Value
If LCase(company) = "A" Then
Call SubroutineA
Exit Sub
End If
If LCase(company) = "B" Then
Call SubroutineB
Exit Sub
End If
Call DefaultSubroutine
End If
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.