[英]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.所以我写了这段代码(它实际上是一个更大的东西的一部分,但这部分给我带来了问题)而且我是 VBA 的新手,所以我不明白为什么它总是返回 0 作为公式结果。
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.顺便说一句,我测试了各种日期,所有日期都返回 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.是数学表达式 - 1除以9除以1996 - 当强制转换为 integer 类型时将为零。
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.您需要使用 DateSerial 将所有日期转换为整数,然后进行比较。
No spaces, proper # separator, and VBA always expects american (m/d/yy) format, so for september 1, use #9/1/1996#
.没有空格,正确的 # 分隔符和 VBA 总是需要美国(m/d/yy)格式,所以对于 9 月 1 日,使用
#9/1/1996#
。
Just to share knowledge... you can also use the CDate
function.只是为了分享知识……您也可以使用
CDate
function。 It works pretty well and also accepts other date formats, as CDate("01/Sep/1996")
.它工作得很好,也接受其他日期格式,如
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).
如果您在不同的区域设置(例如全球应用程序)下使用它,处理日期可能会变得很痛苦。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.