Excel vba:日期函数返回;00:00:00“;
如果传递的值“DateValue”为空,我下面的代码将返回“00:00:00” vba:Excel vba:日期函数返回;00:00:00“;,excel,vba,Excel,Vba,如果传递的值“DateValue”为空,我下面的代码将返回“00:00:00” vba: 公共函数forDate(ByVal DateValue作为字符串)作为日期 月桂 如果不为null(DateValue)和DateValue“”,则 DoDate=CDate(FormatDateTime(DateValue,1,10)) forDate=十二酸盐 如果结束 端函数 “DateValue”为空时如何处理??? 请给出答案。我认为解决方案可能是使用变量参数声明函数| Public Funct
公共函数forDate(ByVal DateValue作为字符串)作为日期
月桂
如果不为null(DateValue)和DateValue“”,则
DoDate=CDate(FormatDateTime(DateValue,1,10))
forDate=十二酸盐
如果结束
端函数
“DateValue”为空时如何处理???
请给出答案。我认为解决方案可能是使用变量参数声明函数|
Public Function forDate(DateValue)
当VBA将NULL转换为字符串时,它不再为NULL…请参阅注释以了解解决方案
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
公共函数forDate(ByVal DateValue作为字符串)As Date'将只接受字符串参数
端函数
'下面的函数是一个变量,可以接受字符串null
公共函数forDate(日期值)
月桂
如果DateValue&“”,则这将处理null和空字符串
其他的
'将在null或空字符串时转到此处
DateValue=Null
如果结束
端函数
如果您使用vbNull
而不是null
,则将日期设置为null是有效的(即运行时不会出错)。尽管它将返回#12/31/1899#
,而不是null
本身。稍后,您可以根据已知的空值检查日期变量,将其作为伪空值
或者您可以将其设置为最小日期DateSerial(100,1,1)
,它将返回#1/1/100
,这将处理空字符串和/或空字符串:
Public Function forDate(ByVal DateValue)
If IsDate(DateValue) Then
forDate = CDate(DateValue)
Else
forDate = CVErr(xlErrValue)
End If
End Function
注意,我已经删除了变量的定义,以允许正确传递NULL。在电子表格中用作函数时,该函数将返回一个#值如果传递了无法表示为日期的字符串,则代码>错误
示例结果:
函数IsNullDate(ByVal d作为日期)为布尔值
如果d=CDate(“00:00:00”),则
IsNullDate=True
其他的
IsNullDate=False
如果结束
端函数
子检查日期()
尺寸d1、d2为日期
d1=日期
d2=空
MsgBox“d1=”&IsNullDate(d1)和“,d2=”&IsNullDate(d2)
端接头
运行CheckDate()
具有以下输出:
d1=假,d2=真
如前所述,您的函数没有为您想要的情况定义返回值-您至少需要一个'else'语句?,,您的意思是当'DateValue'为'Null'时,还是当变量'DateValue'的值为四个leter单词“Null”时?@CaBieberach:when“DateValue”变量的值为“Null”时@user2002774为什么不在调用函数之前验证DateValue
字符串?这意味着您将在函数中调用此函数。如果为NULL,则返回空字符串,否则可以返回日期
格式。因为您将日期值作为字符串进行了dimeted(ByVal DateValue作为字符串
),所以不能将NULL作为参数传递。如果你尝试这样做,VBA将引发一个错误,该函数将不会被evaluaterd。弗洛里斯:不,我不能这样做,它必须是日期格式。我对其他格式有问题。请确保您的函数接受null并返回null…它会工作。您不能使用=
分配null-您必须设置它。虽然…vbNull
与“Null”不同,但不确定是否可以将日期设置为NullvbNull
是一个VBA内部常量,值为1。@CaBieberach你说得对!(有点误导…)那么,如果他坚持返回一个Date
Public Function forDate(ByVal DateValue)
If IsDate(DateValue) Then
forDate = CDate(DateValue)
Else
forDate = CVErr(xlErrValue)
End If
End Function