The following Excel VBA code compares the effect of accumulating hours (1/24 of a day) in a Variant array with Date members, and in a Date array. I have columns C, E, G formatted as Date and D, F, H as Number with a lot of d.p.s. In columns A and B I replicated the calculation using worksheet functions. You probably won't believe this until you try it, but the last output from the Variant array of Date is 1 day early. The numeric value, which is reported as 39814.9999999999 by VBA, is converted to 39814 in Excel.
Edit: when I say columns C, E, G in Date format, I mean Custom "dd/mm/yyyy hh:mm:ss.00".
Has anybody seen this before? But more importantly, how do I know what I can trust when using Variants? I have tens of thousands of lines to maintain and Variant arrays are used everywhere that we need to do intensive processing on the Excel data.
Sub FillDatesBug()
Dim dtHours() As Date
Dim vHours As Variant
Dim vHours2 As Variant
Dim dtHour As Date
Dim dHour As Double
Dim i As Long
ReDim dtHours(1 To 25, 1 To 1)
ReDim vHours(1 To 25, 1 To 1)
ReDim vHours2(1 To 25, 1 To 1)
dtHour = CDate(1 / 24)
dHour = 1 / 24
dtHours(1, 1) = CDate(39814)
vHours(1, 1) = CDate(39814)
vHours2(1, 1) = 39814#
For i = 2 To 25
dtHours(i, 1) = dtHours(i - 1, 1) + dtHour
vHours(i, 1) = vHours(i - 1, 1) + dtHour
vHours2(i, 1) = vHours2(i - 1, 1) + dHour
Next i
Range("C2:C26").Value = dtHours
Range("D2:D26").Value = dtHours
Range("E2:E26").Value = vHours
Range("F2:F26").Value = vHours
Range("G2:G26").Value = vHours2
Range("H2:H26").Value = vHours2
Range("C28").Value = "dtHours(25,1) = " & dtHours(25, 1) & " or " & CDbl(dtHours(25, 1))
Range("E28").Value = "vHours(25,1) = " & vHours(25, 1) & " or " & CDbl(vHours(25, 1))
Range("G28").Value = "vHours2(25,1) = " & Format(vHours2(25, 1), "dd/mm/yyyy hh:mm:ss") & " or " & vHours2(25, 1)
End Sub
And here's a screenshot - I don't have the rep to display it, apparently.
As you can see, a Date array and a Variant array with Double members get the right answers (including the perfectly normal and understood numerical error). Certain values in a Variant array with Date members get translated into Excel wrongly.
First person to actually see what I'm saying here wins my eternal gratitude.