从混合字符串中提取格式错误的日期并转换为YYYY-MM-DD

时间:2014-03-26 13:58:45

标签: excel vba validation date datetime

我很好地寻找了这个,但我找不到它,这让我感到惊讶。 我有一个古老的表格,必须导入,其中一个字段是“日期和位置”。我必须从中提取日期,这可能是各种格式,具体取决于作者。包含位置意味着它可以包含不同长度的文本。

数据示例如下:

  • 流程24/03/14 @ 15:30
  • 存档24/03/2014 @ 15.45
  • Matal 24/03/2014 @ 11:30
  • 13.03.14 Falkirk
  • Process @ 11:21 11/03/14
  • Intake @ 08; 47 20/02/14
  • Raw Intake Laboratory DOP:08.01.13 @ 15:30

1 个答案:

答案 0 :(得分:0)

以下是我解决问题的方法:

Public RawTestLocation, testLocation, testDate, autoDate, As String
Sub GetDate()
'Really this just needs the date and test location fields on the report sheet to be separated



RawTestLocation = ActiveSheet.Range("b44").Value

'remove the time which user S adds after an @ sometimes, because it occasionally uses . instead of : for the divider.
If InStr(RawTestLocation, "@") <> 0 Then testLocation = Left(RawTestLocation, InStr(RawTestLocation, "@") - 1)


'Prevent full stop at the end causing an error
If Right(testLocation, 1) = "." Then
    testLocation = Left(testLocation, Len(testLocation) - 1)
End If


'format date in standard format
If testLocation = "" Then testLocation = RawTestLocation
testLocation = Replace(testLocation, ".", "/")



'check for date in middle of string

    Dim StartOfDate As Integer
    LastSlashInDate = InStrRev(testLocation, "/") - 5

    testDate = Mid(testLocation, LastSlashInDate, 10)

    If Not IsDate(testDate) = True Then
        testDate = Mid(testLocation, LastSlashInDate, 8)
    End If

'check for date at beginning of string
    If Not IsDate(testDate) = True Then
        testDate = Right(testLocation, 16)
    End If

    If Not IsDate(testDate) = True Then
        testDate = Left(testLocation, 10)
    End If

    If Not IsDate(testDate) = True Then
        testDate = Left(testLocation, 8)
    End If

'Check for date at end of string
    If Not IsDate(testDate) = True Then
        testDate = Right(testLocation, 10)
    End If

    If Not IsDate(testDate) = True Then
        testDate = Right(testLocation, 8)
    End If


If IsDate(testDate) = True Then
    testDate = CDate(testDate)
    autoDate = True
End If
End Sub

因此子通过识别字符串中的最后一个来检查日期。如果失败,它会查看任何日期格式的结尾,然后是开头。不同的数字(8,10和16)用于检查DD / MM / YY,DD / MM / YYYY和DD / MM / YY 00:00格式。