【问题标题】:VBA - How to speed up Loop with dates?VBA - 如何用日期加速循环?
【发布时间】:2016-10-07 20:50:40
【问题描述】:

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

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

例如:2016 年 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

【问题讨论】:

  • 如果您的代码按预期工作,但速度很慢,并且您希望加快它的速度并使其整体更简洁、更好,请知道 Code Review 正是这样做的。
  • 日期是一个浮点数。你可以加 1 加一天。这将避免使用Days(i) = DateSerial(dtTrickle_Year, dtTrickle_Month, i)。这节省了一个看起来要进行大量处理的函数调用。所以创建一个变量d。在你的循环中d=d+1.

标签: vba excel loops date nested-loops


【解决方案1】:

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

【讨论】:

  • 感谢您的建议。不知道我知道该怎么做,你能指出我的任何指导方针吗?
  • 关于 SO 的许多示例。尝试搜索变体数组
猜你喜欢
  • 2019-05-15
  • 2018-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多