如何搜索使用VBA字符串中的日期时间的最后一次出现?
在下面我的样本,在A列中,有有日期时间戳笔记。我需要获得日期时间的最后一次出现。如果只注意事项只包含1个日期时间的话,我需要得到。预期的输出是列B.
我试图让日期时间,但它是获得第一个出现。请看下文中我的代码:
Sub test()
For x = 1 To Cells(Rows.Count, 1).End(xlUp).Row
Cells(x, 2).Value = Left(Cells(x, 1).Value, 19)
Cells(x, 2).Select
Selection.NumberFormat = "yyyy-mm-dd hh:mm:ss"
Next x
End Sub
我相信这应该做你在找什么。您可以拆分单元格的内容,并退出当你发现第一个有效日期后循环倒退。
Option Explicit
Private Function GetLastDate(TextRange As Range) As String
Dim textToParse As String: textToParse = TextRange.Value
Dim textArray As Variant: textArray = Split(textToParse, vbLf)
Dim possibleDate As Variant
Dim i As Long
Dim j As Long
Const textToSplit = " - "
'Loop backwards
For i = UBound(textArray) To LBound(textArray) Step -1
'A Dash Exists
If (InStr(1, textArray(i), textToSplit) > 0) Then
possibleDate = Split(textArray(i), textToSplit)
'Loop forwards
For j = LBound(possibleDate) To UBound(possibleDate)
'If it is a date exit
If IsDate(Trim(possibleDate(j))) Then
GetLastDate = Trim(possibleDate(j))
Exit Function
End If
Next
End If
Next
End Function
Sub Example()
Dim rng As Range: Set rng = ThisWorkbook.Sheets("Sheet1").Range("a1")
Debug.Print "the last date is: " & GetLastDate(rng)
End Sub
这也可以使用公式进行,例如,我中A1以下
"01/02/2019 testing
04/05/19 test stage
05/09/2019 test3"
并使用以下公式
=MID(A1,FIND("@",SUBSTITUTE(A1,"/","@",LEN(A1)-LEN(SUBSTITUTE(A1,"/",""))-1))-2,10)
我得到
05/09/2019
希望这可以帮助。