Reputation: 525
So I wrote this piece of code (it's actually part of a something bigger but this part gives me the problems) and I'm new to VBA so I can't figure out why this always returns 0 as the formula result.
Function test(begindatum As Date, einddatum As Date)
Dim Days1
If begindatum < 1 / 9 / 1996 And begindatum > 31 / 7 / 1986 Then
If einddatum > 31 / 8 / 1996 Then
Days1 = DateDiff("d", 1 / 9 / 1996, begindatum)
Else: Days1 = DateDiff("d", einddatum, begindatum)
End If
End If
test = Days1
End Function
I tested with various dates btw, all of them returned the output 0.
Would appreciate it if someone could point out where I went wrong.
Kindly regards,
Daquicker
Upvotes: 0
Views: 113
Reputation: 25272
No spaces, proper # separator, and VBA always expects american (m/d/yy) format, so for september 1, use #9/1/1996#
.
Upvotes: 0
Reputation: 2097
Just to share knowledge... you can also use the CDate
function. It works pretty well and also accepts other date formats, as CDate("01/Sep/1996")
.
Pay attention, however. Handle date may become a pain if you'll use it under different regional settings (global apps, for instance).
Upvotes: 0
Reputation: 17451
You need to use DateSerial to convert all dates to integers, then compare them.
Upvotes: 2
Reputation: 175896
Your dates;
1 / 9 / 1996
are mathematical expressions - 1 divided-by 9 divided by 1996 - which will be zero when coerced to an integer type.
for a literal date use:
If begindatum < #1/9/1996# and ...
Upvotes: 3