Search code examples
vbaexcelloopsdatenested-loops

VBA - How to speed up Loop with dates?


Looking for ideas on how to optimize this code to run faster. Current code works but table is too large and performance speed is slow.

Overall logic: determine number of days in a month. Loop through table(wsUploadTable) and increment value if condition is met. Loop to next day in month and repeat.

For example: 10/1/2016, loops through table for date match and increment value. Next date, 10/2/2016 loop table for match...til last day of month 10/31/2016, loop table, find match and increment value

'Determine DaysinMonth and assign DaysinMonth_Distro value
DaysInMonth = DateSerial(dtTrickle_Year, dtTrickle_Month + 1, 1) - _
              DateSerial(dtTrickle_Year, dtTrickle_Month, 1)
DoM_Distro = 1 / DaysInMonth

ReDim Days(1 To DaysInMonth)
For i = 1 To DaysInMonth
    Days(i) = DateSerial(dtTrickle_Year, dtTrickle_Month, i)

   'Loop Upload Table and increment cell value if condition is met
    With wsUploadTable
    lngER_PrimaryID = .Cells(1048576, 2).End(xlUp).Row
    For intPrimaryID = 2 To lngER_PrimaryID
        'store current cell value
        dblLeadsValue = .Cells(intPrimaryID, col_Upload_Leads)
        'match UploadTable row on user input and increment new value 
            If.Cells(intPrimaryID, 3).Value = Days(i) Then
            .Cells(intPrimaryID, 11).Value = dblLeadsValue + (x * x * DoM_Distro)
        End If
    Next 'Next PrimaryID
    End With
Next i

Solution

  • Store the table column into an array (1 read operation), loop through the array and store the calculations in the array, write the result values back into the table (1 write operation). That will be a lot faster than a read and a write for every row in the table.