I have an array of data on one worksheet. I need to loop through the array, evaluate each row based on certain criteria, and then take the criteria matched rows and copy them over to another worksheet. I wrote the following code to do this process.
However, the loop takes too long. It takes about 5 minutes to run. I need it to run in less than 30 seconds. I read the following q on SO: What is the most efficient/quickest way to loop through rows in VBA (excel)? and that lead me to create the array. I also tried to keep the code simple. I turn off screenupdating and enableevents.
What can I do to make this process faster? Thank you for your help.
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
Applicationrelated tips to help performance areApplication.Calculation = xlCalculationManualandApplication.DisplayAlerts = False. But in your case I'm not sure those would help a whole lotIfstatements withAndand use aFor Eachloop to loop through the rows you want to evaluate.Application.Calculation = xlCalculationAutomatic, otherwise whenever you manually enter a formula and copy it, it will paste the original result each time. Same withDisplayAlerts(=True)