vba:日期函数返回“00:00:00”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15111218/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 19:48:29  来源:igfitidea点击:

vba: date function returns "00:00:00"

excel-vbavbaexcel

提问by user2002774

My below code returns "00:00:00", if passed value "DateValue" is null

我下面的代码返回“00:00:00”,如果传递的值“DateValue”为空

vba:

VB:

Public Function forDate(ByVal DateValue As String) As Date
Dim DoDate As Date
If Not IsNull(DateValue) And DateValue <> "" Then
DoDate = CDate(FormatDateTime(DateValue, 1, 10))
forDate = DoDate
End If
End Function

How to handle when "DateValue" is null??? please suggest an answer.

“DateValue”为空时如何处理???请提出一个答案。

回答by Brad

setting a Dateto null is valid (i.e. will run without error) provided you use vbNulland not Null. Though it will return #12/31/1899#and not nullitself. You can check you date variable against that known null value later as being your pseudo null value.

将 a 设置Date为 null 是有效的(即运行时不会出错),前提是您使用vbNull而不是Null。虽然它会返回#12/31/1899#而不是null它自己。您可以稍后根据该已知空值检查日期变量作为伪空值。

Or you could set it to the minimum date DateSerial(100, 1, 1)which will return #1/1/100#

或者您可以将其设置为DateSerial(100, 1, 1)将返回的最小日期#1/1/100#

回答by SeanC

This will handle null and/or empty strings:

这将处理空和/或空字符串:

Public Function forDate(ByVal DateValue)
If IsDate(DateValue) Then
    forDate = CDate(DateValue)
Else
    forDate = CVErr(xlErrValue)
End If
End Function

Notice I have removed the definitions of the variables to allow NULL to be passed correctly. when used as a function in a spreadsheet, the function will return a #VALUE!error if a string that cannot be represented as a date is passed

请注意,我删除了变量的定义以允许正确传递 NULL。在电子表格中用作函数时,#VALUE!如果传递了无法表示为日期的字符串,则该函数将返回错误

Example results:
exaple

示例结果:
例子

回答by Floris

I think the solution may be to declare the function with a variant parameter|

我认为解决方案可能是声明带有变体参数的函数|

Public Function forDate(DateValue)

When VBA converts NULL to String, it is no longer NULL...

当 VBA 将 NULL 转换为 String 时,它不再是 NULL...

回答by Floris

See the comments for solution

解决办法见评论

Public Function forDate(ByVal DateValue As String) As Date ' will only accept string parameter

End Function

' below function is a variant and can accept string , null 
Public Function forDate(DateValue)
    Dim DoDate As Date
    If DateValue & "" <> "" Then 'this will handle null and empty string


        Else
            'will go here when null or empty string
            DateValue = Null
    End If
End Function