如何在循环遍历10,000个单元格时加快VBA代码的运行速度?
如何在循环遍历10000个单元格时加快VBA代码的运行速度?
问题的原因是代码重复地访问了工作表,每次读取或写入一个单元格。解决方法是使用数组来代替直接访问工作表的方式。
首先,我们可以添加Option Explicit
来强制声明所有变量,这将使代码更易读,错误更容易追踪。接下来,我们可以使用数组来存储数据并进行计算,然后一次性将结果写入工作表。
下面是使用数组的代码示例:
Option Explicit Sub GMC2() ' 工作表 Const wsName As String = "Speeder premium" Const fRow As Long = 2 Const rCount As Long = 10000 Const sCol As Long = 32 Const dCol As Long = 33 ' 数据 Const Strike As Long = 100 Const Cap As Long = 120 Const Part As Double = 3.25 Const KO As Long = 60 ' 定义工作簿 Dim wb As Workbook Set wb = ThisWorkbook ' 定义源范围 Dim rng As Range Set rng = wb.Worksheets(wsName).Cells(fRow, sCol).Resize(rCount) ' 将源范围的值写入源数组 Dim Source As Variant Source = rng.Value ' 定义目标数组 Dim Dest As Variant ReDim Dest(1 To rCount, 1 To 1) ' 循环遍历源数组的行,进行计算,并将结果写入目标数组 Dim Curr As Variant Dim i As Long Dim Cash As Double For i = 1 To rCount Curr = Source(i, 1) If Curr >= Cap Then Cash = Strike + (Part * (Cap - Strike)) ElseIf Curr >= Strike And Curr < Cap Then Cash = Strike + (Part * (Curr - Strike)) ElseIf Curr < Strike And Curr >= KO Then Cash = Strike ElseIf Curr < Strike And Curr < KO Then Cash = Curr End If Dest(i, 1) = Cash Next i ' 将目标数组的值写入目标范围 rng.Offset(, dCol - sCol).Value = Dest End Sub
在这段代码中,我们将数据从源范围写入源数组,然后循环遍历源数组的行,进行计算,并将结果写入目标数组。最后,将目标数组的值写入目标范围。
通过使用数组来代替直接访问工作表,我们减少了对工作表的读取和写入次数,从而提高了代码的运行速度。