检查单元格值是date时间(ISO)

想要使用ISO格式(2012-04-12T00:00:00)检查单元格是否为date时间值

目前尝试:

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

它仍然不匹配vba和单元格的格式,因为我有许多具有这种正确格式的单元格,仍然激活else语句,即不能被"####-##-##T##:##:##"

也许yyyy-mm-ddThh-MM-ss?

ISOdate有几种格式,添加星号"####-##-##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中parsingISO8601date/时间(包括TimeZone)

以下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}[AZ]{1}[0-9]{2}\:[0-9]{2}\:[0-9]{2}" IsISODateTime = .Test(str) End With End Function 

UDF返回一个真正的布尔值True / False。

我提供的模式是非常一砖一瓦的文字; 可以使用Microsoft Excel中的“ 如何使用正则expression式(正则expression式)”中详细介绍的方法缩小内部单元格和循环中的方法 。


¹ 用户定义function(aka UDF)被放入标准模块代码表中。 点击Alt + F11 ,当VBE打开时,立即使用下拉菜单来插入►模块Alt + IM )。 将function代码粘贴到名为Book1 – Module1(Code)的新模块代码表中。 点击Alt + Q返回到您的工作表。

正如Tim Williams所指出的那样,

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

要testing格式为ISO格式的date,你应该检查单元格的NumberFormat属性,所以你的If语句应该是:

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

注意:如果当前接受的解决scheme正在工作,那么您的单元格只包含string值( 看起来像ISO格式的date),而不是使用ISOdate格式显示的实际date。