开发者

What's wrong with this piece of VBA code that should return a number of days?

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


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 ...


You need to use DateSerial to convert all dates to integers, then compare them.


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


No spaces, proper # separator, and VBA always expects american (m/d/yy) format, so for september 1, use #9/1/1996#.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜