Excel VBA:按模式在子目录中打开文件

时间:2014-07-13 09:17:10

标签: excel vba

我有一个目录,其文件夹名称如下:

"Voy [yyyymmdd]-[no]"

其中[yyyymmdd]指日期,[no]递增,每个文件夹一个。

dir\Voy 20140101-100\*
dir\Voy 20140105-101\*
dir\Voy 20140109-102\*
dir\Voy 20140113-103\*
dir\Voy 20140117-104\*
dir\Voy 20140121-105\*
dir\Voy 20140125-106\*
[...]

我想在LATEST文件夹中访问一个文件(总是命名为" myfile.xlsx"),即:具有最高[no]的文件

我如何做到这一点? 我应该使用引用here的DIR函数吗?

1 个答案:

答案 0 :(得分:0)

试试这个。您可能需要根据目录和文件命名约定来调整它

Sub GetLatestFiles()
    Dim strDir As String, fs As Object, startFolder As String, subfolder As Object, increment As Integer, latest As Integer, latestFolder As String

    Set fs = CreateObject("Scripting.FileSystemObject")
    startFolder = "C:\YourDirectory"
    Set folder = fs.GetFolder(startFolder)
    latest = 0
    latestFolder = vbNullString        

    For Each subfolder In folder.SubFolders
        increment = CInt(VBA.Right(subfolder.Path, Len(subfolder.Path) - WorksheetFunction.Find("-", subfolder.Path, 1)))

        If increment > latest Then
            latest = increment
            latestFolder = subfolder.Path
        End If
    Next

    Workbooks.Open latestFolder & "\" & "myfile.xlsx"
End Sub
  • 代码循环遍历主目录中的所有子文件夹
  • 每个都记下版本号并跟踪最高
  • 最后打开最新的工作簿