【发布时间】:2016-10-08 16:59:04
【问题描述】:
我在一个工作表上有一组数据。我需要遍历数组,根据特定条件评估每一行,然后获取符合条件的行并将它们复制到另一个工作表。我编写了以下代码来执行此过程。
但是,循环时间过长。运行大约需要 5 分钟。我需要它在 30 秒内运行。我在 SO 上阅读了以下 q:What is the most efficient/quickest way to loop through rows in VBA (excel)?,这导致我创建了数组。我还尝试使代码保持简单。我关闭屏幕更新和启用事件。
我可以做些什么来加快这个过程?感谢您的帮助。
Sub tester()
Dim vData() As Variant
Dim R As Long
Dim C As Long
Dim LastRow1 As Long
Dim rng1 As Range, rng2 As Range
Set sh3 = Sheets("ABC")
Set sh5 = Sheets("XYZ")
Application.ScreenUpdating = False
Application.EnableEvents = False
LastRow1 = sh3.Cells(Rows.Count, "A").End(xlUp).Row
vData = Range("A1:N" & LastRow1).Value
sh5.Range("B3:AV10000").ClearContents
For R = 1 To UBound(vData, 1)
For C = 1 To UBound(vData, 2)
If sh3.Cells(R, "G").Value <= Date Then 'if date is prior to today then
If sh3.Cells(R, "J").Value = "C" Then
If sh3.Cells(R, "D").Value > 0 Then
If sh3.Cells(R, "I").Value >= sh3.Cells(R, "H").Value Then
Set rng1 = sh3.Range("A" & R & ":N" & R)
Set rng2 = sh5.Range("B" & R & ":O" & R)
rng1.Copy rng2
Else
Set rng3 = sh3.Range("A" & R & ":N" & R)
Set rng4 = sh5.Range("B" & R & ":O" & R)
rng3.Copy rng4
End If
ElseIf sh3.Cells(R, "D").Value < 0 Then
If sh3.Cells(R, "I").Value >= sh3.Cells(R, "H").Value Then
Set rng5 = sh3.Range("A" & R & ":N" & R)
Set rng6 = sh5.Range("B" & R & ":O" & R)
rng5.Copy rng6
Else
Set rng7 = sh3.Range("A" & R & ":N" & R)
Set rng8 = sh5.Range("B" & R & ":O" & R)
rng7.Copy rng8
End If
End If
End If
End If
Next C
Next R
Application.ScreenUpdating = True
Application.EnableEvents = True
End Sub
【问题讨论】:
-
另外两个有助于提高性能的
Application相关提示是Application.Calculation = xlCalculationManual和Application.DisplayAlerts = False。但在你的情况下,我不确定这些会有很大帮助 -
老兄! Application.Calculation = xlCalculationManual 工作。从 5+ 分钟到
-
每次编写更改时,工作簿都会重新计算
-
将您的
If语句与And组合起来,并使用For Each循环遍历您要评估的行。 -
一定要在最后加上
Application.Calculation = xlCalculationAutomatic,否则每次手动输入公式复制,都会粘贴原来的结果。与DisplayAlerts(=True) 相同