我有一个保存有以下格式的 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/