VBA - 如何使用日期加快循环?

时间:2016-10-07 20:50:40

标签: vba excel-vba loops date nested-loops

寻找有关如何优化此代码以更快运行的想法。当前代码有效,但表太大,性能速度慢。

总体逻辑:确定一个月内的天数。循环遍历表(wsUploadTable)并在满足条件时增加值。循环到第二天,并重复。

例如:10/1/2016,循环表格以获取日期匹配和增量值。下一个日期,10/2/2016循环表匹配...直到10月31日的最后一天,循环表,查找匹配和增量值

'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

1 个答案:

答案 0 :(得分:4)

将表列存储到数组中(1次读取操作),循环遍历数组并将计算存储在数组中,将结果值写回表中(1次写操作)。这将比表中每一行的读取和写入快得多。