I’m trying to use the DateDiff function for a macro in excel using VBA.
To my understanding the code is supposed to return an integer value.
Here are the examples given online at this location: http://www.techonthenet.com/access/functions/date/datediff.php
-DateDiff (“yyyy”, #15/10/1998#, #22/11/2003#) would return 5
-DateDiff (“m”, #15/10/2003#, #22/11/2003#) would return 1
-DateDiff (“d”, #15/10/2003#, #22/11/2003#) would return 38
Here is the code that I used:
Sub macrotest()
Dim dateNow, dateThen, dateFinal As Date
dateNow = Format(Sheet1.Cells(2, 2), "DD/MM/YY")
dateThen = Format(Sheet1.Cells(3, 2), "DD/MM/YY")
dateFinal = DateDiff("d", dateNow, dateThen)
Sheet1.Cells(5, 2) = dateFinal
End Sub
Lastly, This is what I had in my excel rows:
B2: 5/30/12
B3: 3/30/12
B5: 12:00:00 AM (this cell was supposed to have the result listed).
-I got either dates that excel defaults to, or 12:00.
Any Ideas? Thanks!
According to the help system, DateDiff returns a Long.
Your code declares two Variants and one Date type. Instead of
Dim dateNow, dateThen, dateFinal As Dateyou probably meant
Dim dateNow As Date, dateThen As Date, dateFinal As LongThis code worked for me. You may need to tweak it slightly to apply it to your particular situation (I used ActiveSheet to make the testing go faster)
Also I believe you have
dateNowanddateThenreversed in yourDateDifffunction call.