在Access VBA中使用CDate()的类型不兼容

问题描述 投票:0回答:2

我正在使用VBA计算MS Access中的日期。当我在同一个表单上有两个日期(2016-01-21)时,这种方式可以正常工作,但是当我第一次需要将字符串修改为日期格式时,这样就不行了:20160121 - > 2016-01-21。

这就是我想要做的:

Dim sYear As String, sMonth As String, sDay As String, sDate As String

sYear = Left("20160121", 4)
sMonth = Mid("20160121", 5, 2)
sDay = Mid("20160121", 7, 2)

sDate = sYear & "-" & sMonth & "-" & sDay

MsgBox CDate(sDate)

这将返回错误13,不兼容的类型。

这有效:

MsgBox CDate("2016-01-21")

为什么我的方式不起作用?

vba ms-access
2个回答
1
投票

您必须决定如何处理无效输入值。

一种选择是提供您选择的默认日期,今天的日期或1980-01-01:

Public Function ConvertDate(ByVal TextDate As String) As Date

    Dim RealDate    As Date
    Dim NullDate    As Date

    NullDate = #1/1/1980#

    TextDate = Format(TextDate, "@@@@/@@/@@")
    If IsDate(TextDate) Then
        RealDate = CDate(TextDate)
    Else
        RealDate = NullDate
    End If

    ConvertDate = RealDate

End Function

将返回:

20160121 -> 2016-01-21
20160141 -> 1980-01-01

或者您可以将RealDate的数据类型更改为Variant,并为无效日期返回Null:

Public Function ConvertDate(ByVal TextDate As String) As Variant

    Dim RealDate    As Variant
    Dim NullDate    As Variant

    NullDate = Null     

    TextDate = Format(TextDate, "@@@@/@@/@@")
    If IsDate(TextDate) Then
        RealDate = CDate(TextDate)
    Else
        RealDate = NullDate
    End If

    ConvertDate = RealDate

End Function

将返回:

20160121 -> 2016-01-21
20160141 -> Null

0
投票

错误是因为我测试了错误的日期:12345678。如果日期正确,它可以正常工作......

© www.soinside.com 2019 - 2024. All rights reserved.