VBA: 获取指定文件夹内最新文件的路径

2023-11-03 15:44:23 浏览数 (1)

文章背景: 在工作中,有时想获取文件夹内日期最近的文件,可以借助Dir函数来进行任务的实现。

示例:文件夹内存放有多个不同日期的Excel文件,想要获取最新日期的文件名称和路径。

函数代码:

代码语言:javascript复制
Function getLatestFilePath(origin As String) As String

    '获取最近的文件路径
    
    Dim filename As String, Finalname As String, folder As String
    
    folder = Left(origin, InStrRev(origin, ""))
    
    Finalname = Dir(origin)
    
    filename = Dir(origin)
    
    Do While filename <> ""
    
        If filename > Finalname Then
        
            Finalname = filename
        
        End If
        
        filename = Dir()
        
    Loop
    
    getLatestFilePath = folder & Finalname
    
    Exit Function
    
End Function

Function getLatestFileName(origin As String) As String

    '获取最近的文件名称
    
    Dim filename As String, Finalname As String, folder As String
    
    folder = Left(origin, InStrRev(origin, ""))
    
    Finalname = Dir(origin)
    
    filename = Dir(origin)
    
    Do While filename <> ""
    
        If filename > Finalname Then
        
            Finalname = filename
        
        End If
        
        filename = Dir()
        
    Loop
    
    getLatestFileName = Finalname
    
    Exit Function
    
End Function

Function IsFileExists(path As String) As Boolean

    On Error Resume Next
    If Len(Dir(path)) > 0 Then
    
        IsFileExists = True
        
        Exit Function
        
    Else
    
        IsFileExists = False
        
        Exit Function
        
    End If
    
    If Err.Number <> 0 Then
    
        IsFileExists = False
    
    End If
    
    On Error GoTo 0

End Function

示例的VBA代码:

代码语言:javascript复制
Option Explicit

Sub test()

    Dim Origin_path As String, Object_Path As String, Object_Name As String
    
    Origin_path = "C:Localtest*"
    
    If IsFileExists(Origin_path) Then
    
        Object_Path = getLatestFilePath(Origin_path)
        Object_Name = getLatestFileName(Origin_path)
        
        MsgBox "最新的文件路径:" & Object_Path & vbNewLine & "最新的文件名称:" & Object_Name
    
    Else
    
        MsgBox "路径有误,请确认!"
    
    End If

End Sub

结果展示:

延伸阅读:

(1)InStrRev函数

返回一个字符串在另一个字符串中首次出现的位置(从字符串的末尾开始)。

参考资料:

[1] VBA: 通过Dir函数查找指定文件

[2] InStrRev 函数 (Visual Basic for Applications) | Microsoft Learn(https://learn.microsoft.com/zh-cn/office/vba/language/reference/user-interface-help/instrrev-function

0 人点赞