使用 vba 宏在文本文件中进行日期验证

date validation in a text file using vba macros

我有一个包含连续数据的平面文件(文本文件)。 我需要编写一个宏来验证本文中的日期(从偏移量 7 到 15)。 Is Date() 函数要求输入采用 year/mm/dd 格式,但我所拥有的只是一个如上所述的平面文件。在批处理脚本或 excel 宏中是否有任何解决方案。请帮忙

文本文件如下所示:

aaaaa 20130202 rt bbbbb 20080210 lt cccccc 20150815 gf 

转换为YYYY-MM-DD然后测试:

strLine = "cccccc 20150815 gf"
strDate = Mid$(strLine, 8, 4) & "-" & Mid$(strLine, 12, 2) & "-" & Mid$(strLine, 14, 2)

If IsDate(strDate) Then ...

我首先想到的是正则表达式 (RegEx) 作为此问题的可能解决方案,因为否则提取日期可能会出现问题。

Excel 这里有一些关于如何使用 RegEx 的重要信息: How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

我拼凑了一个快速子例程来测试一个简单的正则表达式来搜索您提供的日期格式。这假定在测试的字符串中没有其他数字字符。您将需要添加对 MS VB 正则表达式的引用(上面的 link 显示了如何)。注意:我故意插入了一个错误的日期“20121313”来测试功能。

Sub doDates()

    Dim strInput As String
    Dim strPattern As String
    Dim strDate As String
    Dim regEx As New RegExp

    strInput = "aaaaa 20121313 rt bbbbb 20080210 lt cccccc 20150815 gf"

    strPattern = "([0-9]){4}([0-9]){2}([0-9]){2}"

    With regEx
        .Global = True
        .MultiLine = False
        .IgnoreCase = False
        .Pattern = strPattern
    End With

    Set collResult = regEx.Execute(strInput)

    For Each testDate In collResult
        strDate = Mid(testDate, 5, 2) & "/" & Right(testDate, 2) & "/" & Left(testDate, 4)
        If Not IsDate(strDate) Then
            MsgBox ("Bad date found: """ & strDate & """")
            Exit Sub
        End If
    Next

    MsgBox ("All dates test ok")

End Sub