检查单元格值是否为日期时间(ISO)



想要使用ISO格式检查单元格是否为日期-时间值,即。2012-04-12T00:00:00

当前尝试:

If mainsht.Cells(r, 6).Value = "" Or mainsht.Cells(r, 6).Value = "####-##-##T##:##:## Then
GoTo next6

尽管如此,它似乎与vba中的格式和单元格值不匹配,因为我有许多具有这种正确格式的单元格,并且仍在激活else语句,即"####-##-##T##:##:##"无法识别。

也许是yyyy-mm-dddThh-mm-ss?

ISO日期有多种格式,添加星号"####-##-##T##:##:##*"会更通用。

2011-01-01T12:00:00Z
2011-01-01T12:00:00+05:00
2011-01-01T12:00:00-05:00
2011-01-01T12:00:00.05381+05:00

示例:

If mainsht.Cells(r, 6).Value = "" Or mainsht.Cells(r, 6).Value Like "####-##-##T##:##:##*" Then 

你可能想看看这篇文章:在Excel 中分析ISO8601日期/时间(包括时区)

以下UDF可以用作VBA工程中的工作表函数或辅助函数。

Option Explicit
Function IsISODateTime(str As String)
    Dim n As Long, nums() As Variant
    Static rgx As Object, cmat As Object
    'with rgx as static, it only has to be created once; beneficial with repeated calls to the UDF
    If rgx Is Nothing Then
        Set rgx = CreateObject("VBScript.RegExp")
    End If
    IsISODateTime = vbNullString
    With rgx
        .Global = False
        .MultiLine = False
        .Pattern = "[0-9]{4}-[0-9]{2}-[0-9]{2}[A-Z]{1}[0-9]{2}:[0-9]{2}:[0-9]{2}"
        IsISODateTime = .Test(str)
    End With
End Function

UDF返回一个true布尔值true/False。

我提供的模式是一砖一瓦的字面意思;可以使用"如何在单元格和循环中使用Microsoft Excel中的正则表达式(Regex)"中详细介绍的方法缩短它。


cco用户定义函数(又名UDF)被放入标准模块代码表中。点击Alt+F11,当VBE打开时,立即使用下拉菜单插入►模块Alt+I1ook1-Module1(code)的新模块代码表中。点击Alt+Q返回工作表

正如Tim Williams已经指出的那样,

If mainsht.Cells(r, 6).Value = "" Or mainsht.Cells(r, 6).Value Like "####-##-##T##:##:##" ...

要测试单元格的ISO格式日期,您应该检查单元格NumberFormat属性,因此您的If语句应该是:

If mainsht.Cells(r, 6).Value = "" Or mainsht.Cells(r, 6).NumberFormat Like "yyyy-mm-ddThh:mm:ss*" Then

注意:如果当前接受的解决方案正在运行,则单元格只包含字符串值(看起来类似于ISO格式的日期),而不是使用ISO日期格式显示的实际日期。

最新更新