VBA从文件路径中提取日期

时间:2019-03-13 12:27:18

标签: excel vba date

我在Excel电子表格中跟踪了一系列文件。它们按日期存储在文件夹中。有时,文件会被更改,然后重新提交,因此文件路径名是可变的。日期格式为常量“ YYYY MM DD”。

示例:

G:\ Inbox \ Folder1 \ Received \ 2019 03 01 \ Final
G:\ Inbox \ Folder1 \ Received \ 2019 03 01 \ 2019 03 02 \ 2019 03 05 \ Final

使用excel VBA,如何仅从文件路径中提取最后一个日期?

2 个答案:

答案 0 :(得分:2)

那可以做到:

Sub test()

Dim MyPath As String, mps As Variant, mps_temp As String, mydate As Date, i As Integer

MyPath = "G:\Inbox\Folder1\Received\2019 03 01\2019 03 02\2019 03 05\Final"
mps = Split(MyPath, "\")

For i = LBound(mps) To UBound(mps)
    mps_temp = mps(UBound(mps) - i)
    If mps_temp Like "#### ## ##" Then
        mydate = DateSerial(Mid(mps_temp, 1, 4), Mid(mps_temp, 6, 2), Mid(mps_temp, 9, 2))
        Exit For
    End If
Next

msgbox mydate 

End Sub

答案 1 :(得分:1)

假设

  1. 最后一个日期位于 \ Final
  2. 之前的位置

考虑:

Sub titan()
    Dim s As String, sDate As String, d As Date

    s = "G:\Inbox\Folder1\Received\2019 03 01\2019 03 02\2019 03 05\Final"
    arr = Split(s, "\")
    sDate = arr(UBound(arr) - 1)
    arr2 = Split(sDate, " ")
    d = DateSerial(arr2(0), arr2(1), arr2(2))
    MsgBox d
End Sub

enter image description here

解析文件路径。抓住倒数第二个元素。转换为日期。