0

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!

JimmyPena
  • 8,694
  • 6
  • 43
  • 64
Mike Kellogg
  • 1,168
  • 5
  • 15
  • 34

1 Answers1

3

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 Date

you probably meant

Dim dateNow As Date, dateThen As Date, dateFinal As Long

This 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)

Sub macrotest()

Dim dateNow As Date, dateThen As Date, dateFinal As Long

dateNow = ActiveSheet.Cells(2, 2).value
dateThen = ActiveSheet.Cells(3, 2).value
dateFinal = DateDiff("d", dateThen, dateNow)

ActiveSheet.Cells(5, 2) = dateFinal

End Sub

Also I believe you have dateNow and dateThen reversed in your DateDiff function call.

JimmyPena
  • 8,694
  • 6
  • 43
  • 64