excel - 意外的 CDate() 行为

标签 excel vba date type-conversion

在浏览一些没有错误处理的旧代码时,我偶然发现了意外的 CDate() function行为。

Sub Test()
    Dim userinput as Variant
    userinput = Application.Inputbox("Enter a date")
    'userinput will be a Variant/String with the inputs below
    Debug.Print CDate(userinput)
End Sub

Input: "27/8", "27/08", "27-8", "27-08", "27.8", "27.08"
Output: 27.08.2019 ' for all of the above

Input: "27.8.", "27.08."
Output: 04.10.1900, 31.05.1907

我要么期待 Error 13: Type-mismatch , 或 27.08.190027.08.2019作为输出。
后两个输入发生了什么?我无法绕过它。
Additional input: "26.8." -> output: 24.09.1900
Input: "26.08." -> output: 20.02.1907

区域设置为 German (Germany) (Deutsch (Deutschland))
日期格式为 DD.MM.YYYY
编辑:
完整的用户输入代码如下所示:
Sub Test()
    Dim userinput As Variant
    Dim cancelBool As Boolean
    Do While Not ((IsDate(userinput) And Not userinput = vbNullString) Or cancelBool)
        userinput = Application.InputBox("Enter a date")
        If userinput = False Then cancelBool = True
        'the following line was inspired by Plutian
        If Not IsDate(userinput) And IsNumeric(userinput) Then userinput = userinput & Year(Now())
    Loop
    If Not cancelBool Then Debug.Print CDate(userinput)
End Sub

最佳答案

这似乎不是 CDate 行为问题,只是一般问题的文本到数字转换。

我没有引用,但根据观察:当尝试将文本转换为数值时,Excel 将检查文本是否是明显的日期。如果不是,它将删除任何千位分隔符 - 毫无疑问,还有本地货币符号和其他东西 - 以尽可能将文本减少为一个数字。

因此,在我的英语语言环境设置中:
"27.8" ( "27,8" 在你的)是一个可识别的十进制值
= 27 天和 8/10 过去 31/12/1899 = 26/01/1900 19:12:00"27,8" ("27.8" 在你的)是一个不可识别的十进制值,也不是一个可识别的日期
所以它变成了"278"因为它去掉了 000 分隔符(我的设置是逗号,你的设置是句点)
过去 278 天 31/12/1899 = 27/09/1900
然而,正如@Nacorid 所指出的,CDATE对此略有不同(与标准转换)并尝试将其解决为一个日期 - 8 月 27 日(当年)。
"27.8." (你的 "27,8," )抛出一个错误,因为它是一个不可识别的日期,并且由于两个十进制指针,Error被生产。
"27,8," (您的 "27.8.")不是可识别的日期,Excel 假定需要删除 000 分隔符,因此将其转换为 278
=过去 278 天 31/12/1899 = 04/10/1900
所以,TL;DR 是 "27.8." - 虽然在德语中可以接受作为日期 - Excel 不能接受,您需要捕获这些并添加假设的年份或类似的时间来解决它。

或者,考虑添加一个日历弹出表单,强制用户提供日、月和年。

关于excel - 意外的 CDate() 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57670002/

相关文章:

打开文件时未启用 Excel ActiveX 列表框

mysql - mysql 中的默认日期

excel - 有没有办法将 Excel 文件嵌入到我的可执行 (exe) 文件中?

excel - 什么表明 Office Open XML 单元格包含日期/时间值?

vba - 错误 400 消息 - 不知道如何解决公式

javascript - Moment.js 添加多个日期之间的差异

javascript - 按英国日期对 jQuery 数据表进行排序并忽略空单元格

vba - 在 VBA 中复制和粘贴过滤的行

Excel VBA - 搜索范围 - 如果单元格包含文本然后复制单元格 - 粘贴偏移量 2,1

excel - 有没有更聪明的方法来解决几个列