如何使用 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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句