2

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

vba:

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

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

4

5 回答 5

1

Date如果您使用而vbNull不是Null. 虽然它会返回#12/31/1899#而不是null它自己。您可以稍后将日期变量与该已知空值检查为您的伪空值。

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

于 2013-02-27T13:37:59.800 回答
1

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

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

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

示例结果:
例如

于 2013-02-27T20:55:59.887 回答
0

我认为解决方案可能是使用变体参数声明函数|

Public Function forDate(DateValue)

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

于 2013-02-27T11:47:45.313 回答
0

解决方法见评论

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
于 2013-02-27T11:48:55.790 回答
0
Function IsNullDate(ByVal d As Date) As Boolean
    If d = CDate("00:00:00") Then
        IsNullDate = True
    Else
        IsNullDate = False
    End If
End Function

Sub CheckDate()
    Dim d1, d2 As Date
    d1 = Date
    d2 = Empty
    MsgBox "d1= " & IsNullDate(d1) & ",  d2=  " & IsNullDate(d2)
End Sub

运行CheckDate()有以下输出:

d1=假,d2=真

于 2020-07-05T12:20:37.467 回答