2016-10-07 37 views
0

尋找關於如何優化此代碼以更快運行的想法。目前的代碼工作,但表格太大,性能速度很慢。VBA - 如何加快與日期循環?

總體邏輯:確定一個月中的天數。循環訪問表(wsUploadTable)並在滿足條件時增加值。在月中循環到第二天並重復。

例如:10/1/2016,通過表格循環查找日期匹配和增量值。接下來日期,比賽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 
+2

如果您的代碼按預期工作,但速度很慢,而且您希望加快速度並使其整體更清潔和更好,請了解[codereview.se]的確如此。 –

+0

A日期是一個浮點數。你可以添加1來添加一天。這將避免使用'Days(i)= DateSerial(dtTrickle_Year,dtTrickle_Month,i)'。這樣可以節省一個看起來需要很多處理的函數調用。所以創建一個變量'd'。在你的循環中'd = d + 1'。 –

回答

4

存儲表列到一個數組(1讀取操作),遍歷數組並將計算結果存儲在數組中,將結果值寫回表中(1次寫入操作)。這將比表中每一行的讀取和寫入快得多。

+0

感謝您的建議。不知道我知道如何做到這一點,你能指出我的任何援助準則嗎? – emmanueledu

+0

SO上的很多例子。嘗試搜索Variant數組 –