根据预期名称选择文件

时间:2018-03-21 12:47:23

标签: vba excel-vba excel

我正在尝试根据在VBA中仅部分完成的名称打开文件。这是一个例子:

我想提取一个名为“MMM B2 06222018”

的文件

该文件将始终位于“C:\ Myfile \”

但是,这两个文件保存在“C:\ Myfile \”:

“MMM B2 06222018已更新” - 10:00更新

“MMM B2 06222018” - 9:00更新

我想要的是宏在文件名中提取名称为“MMM B2 06222018”的最近更新的文件,但该名称可能是也可能不是文件的完整名称。在这种情况下,“MMM B2 06222018 Updated”是我想要提取的文件,因为它包含所有“MMM B2 06222018”名称,并且它是最近保存的文件。

FileDateTime(file_path) 'I was thinking of using this to compare the file save times. 
'But I can only use this if I have a file name.

分析部分文件名的好方法是什么?

谢谢!

2 个答案:

答案 0 :(得分:3)

Function GET_LATEST_FILE(strFolder As String, strWildCardStart As String) As String

Dim d As Date, fld as Object, f As Object

d = DateSerial(1900, 1, 1)

With CreateObject("scripting.filesystemobject")
    Set fld = .getfolder(strFolder)
    For Each f In fld.Files
        If f.Name Like strWildCardStart & "*" Then
            If f.datelastmodified > d Then
                d = f.datelastmodified
                GET_LATEST_FILE = f.Name
            End If
        End If
    Next f
End With

End Function

像这样使用

GET_LATEST_FILE("C:\Workspace\Dummy Data","Sample")

答案 1 :(得分:0)

在没有FileSystemObject的情况下,执行此操作的一种不太强大的方法是使用Dir

Function GetLatestFile(ByVal FolderName As String, ByVal FileName As String) As String
    GetLatestFile = "" 'Default to blank

    'Declare variables
    Dim sTestFile As String, dTestFile As Date, dLatest As Date

    If Right(FolderName, 1) <> "\" Then FolderName = FolderName & "\" 'Add final slash if missing
    If Len(FileName) = Len(Replace(FileName, "*", "")) Then FileName = FileName & "*" 'Add wildcard if missing
    dLatest = DateSerial(1900, 0, 0) 'Default to 0

    sTestFile = Dir(FolderName & sTestFile) 'First file that matches the filename, if any
    While Len(sTestFile) > 1 'Loop through all files until we run out
        dTestFile = FileDateTime(FolderName & sTestFile) 'Get Created/Modifed Date
        If dTestFile > dLatest Then 'If new file is newer
            GetLatestFile = sTestFile
            dLatest = dTestFile 'Store date
        End If
        sTestFile = Dir() 'Calling Dir without any arguments gets the next file to match the last filename given
    Wend
End Function