excel - 如何根据文件名模式使用最新的文件?

标签 excel vba

我有一个保存有以下格式的 Excel 文件的文件夹:

  • 2018.01 final.xlsx
  • 2018.02 final.xlsx
  • 2018.03 final xlsx.
  • 等等...

  • 我想执行 VLOOKUP根据文件名模式查找最新的文件。今天应该是 2018.08 final xlsx .
    如果尚未保存八月文件,我想使用上个月,即七月 (2018.07 final.xlsx)。
    以下代码打开最新文件。我想要根据模式的最新文件,而不打开它。
      fromPath = Sheets("Open latest file").Range("B5")
      fromPath2 = Sheets("Open latest file").Range("B6")
    
      If Dir(fromPath) = "" Then
    
        Workbooks.Open (fromPath2)
    
      Else
    
        Workbooks.Open (fromPath)
    
      End If
    
    End Sub
    

    最佳答案

    幸运的是,我已经有了一个我喜欢使用的功能,它基本上可以满足您的需求:

    Function GetMostRecentExcelFile(ByVal myDirectory As String, ByVal filePattern As String) As String
    
        Dim fso As Object
        Set fso = CreateObject("Scripting.FileSystemObject")
    
        Dim myFolder As Object
        Set myFolder = fso.getfolder(IIf(Right(myDirectory, 1) = "\", myDirectory, myDirectory & "\"))
    
        Dim currentDate As Date
        Dim fname As String
    
        Dim currentFile As Object
        For Each currentFile In myFolder.Files
            If (currentDate = CDate(0) Or currentFile.DateCreated > currentDate) And currentFile.name Like filePattern _
                And InStr(LCase$(currentFile.name), ".xlsx") > 0 And InStr(currentFile.name, "~$") = 0 Then
    
                currentDate = currentFile.DateCreated
                fname = currentFile.name
    
            End If
        Next currentFile
    
        GetMostRecentExcelFile = fname
    
    End Function
    

    它将遍历指定的myDirectory查找与 filePattern 匹配的任何文件您提供并将返回具有与所述模式匹配的最新创建文件的文件。

    注意:它不根据文件名选择文件,仅根据文件的CreationDate !!

    以下是您最有可能使用它来解决问题的方法:
    Sub Main()
    
        Dim pattern As String
        pattern = "*20##.## final*"
    
        Dim path As String
        path = sheets("Open latest file").Range("B5").Value2
    
        Dim filename As String
        filename = GetMostRecentExcelFile(path, pattern)
    
        If Len(filename) = 0 Or Len(Dir(filename)) = 0 Then
            path = sheets("Open latest file").Range("B6").Value2
            filename = GetMostRecentExcelFile(path, pattern)
        End If
    
        If Len(filename) > 0 Then
            Workbooks.Open (IIf(Right(path, 1) = "\", path, path & "\") & filename)
        Else
            MsgBox "No files found matching pattern"
        End If
    
    End Sub
    

    关于excel - 如何根据文件名模式使用最新的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52058209/

    相关文章:

    Excel 打印带有正确小数分隔符的数字

    excel - 我不明白 XlSaveAsAccessMode 是什么,有人可以解释一下吗?

    vba - 运行循环以禁用控件时 Excel 崩溃

    excel - 如何在索引匹配或等效项中使用变量搜索范围?

    database - 使用 Access.Application 对象与数据库连接之间的区别

    arrays - 在 VBA 中定义文字二维字符串数组

    excel - 使用工作表列中的地址发送电子邮件

    vba - 在 VBA 中,所有变量都以变体类型开始吗

    excel - 通过 VBA 将文档上传到 SharePoint

    python - 如何使用工作或学校帐户在 Python 中读取 SharePoint Online (Office365) Excel 文件?