VBA可以通过阅读其名称来打开最新的电子表格吗?

时间:2017-12-12 18:21:51

标签: vba excel-vba excel

我从我的IT部门收到每周一次的Excel文件,其中包含员工,主管,部门等的更新列表。每周,我都会将文件从电子邮件拖到计算机上的指定文件夹中。

有时候,我希望VBA脚本能够引用和复制IT最近发送给我的最新版本的信息。该文件的命名约定始终相同:“EmployeeListing_20171211”,但显然名称中的日期是文件生成的任何一天。所以下周,我可以预期新文件名为“EmployeeListing_20171218。”

因为这些文件存储在共享文件夹中,所以我无法知道其他人是否正在打开&修改它们,所以我不希望脚本通过最近修改日期,而是能够从文件名中读取日期并选择最新的文件。我看到的与此相关的所有问题似乎都指向打开具有最新修改日期的文件,而不是其名称包含最近日期的文件。

要做到这一点,在我看来,我需要读取文件夹中所有文件的名称,告诉VBA如何将字符串转换为日期,找到最新的日期,然后找到与此日期匹配的相应Excel文件。但我不知道从哪里开始。任何人都可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

这里有一些代码可以帮助您入门。

Sub test()

    Dim sFile As String
    Dim sPath As String
    Dim dtFile As Date
    Dim dtMax As Date, sMax As String
    Dim sDate As String

    'Folder where your files live
    sPath = Environ("userprofile") & "\Documents\MyFolder\"

    'Get the first file that starts with EmployeeListing_
    sFile = Dir(sPath & "EmployeeListing_*")

    'If there are no files, the lenght = 0
    Do While Len(sFile) > 0
        sDate = Split(sFile, "_")(1) 'get the date part of the file name

        'turn it into an actual date
        dtFile = DateSerial(Left$(sDate, 4), Mid$(sDate, 5, 2), Mid(sDate, 7, 2))

        'if it's bigger than any others, store the date and name
        If dtFile > dtMax Then
            dtMax = dtFile
            sMax = sFile
        End If
        'no arguments means get the next file using the same arguments as
        'previosly supplied
        sFile = Dir
    Loop

    'Print the file with the biggest date
    Debug.Print sPath & sMax

End Sub