我如何获得该程序以名称中的date打开上次修改date工作簿

我的文件都被命名为MyFile053017.xlsmyfile052517.xls

我试图抓住名称中的date,并将其用作最后修改date,以防某人打开并保存其中一个工作簿

'Force the explicit delcaration of variables Option Explicit Sub OpenLatestFile() 'Declare the variables Dim MyPath As String Dim MyFile As String Dim LatestFile As String Dim LatestDate As Date Dim LMD As Date 'Specify the path to the folder MyPath = "M:\Users\Dan\Access\DiscontinueQuerry\DiscontinueQuerrySave\" 'Make sure that the path ends in a backslash If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\" 'Get the first Excel file from the folder MyFile = Dir(MyPath & "*.xls", vbNormal) 'If no files were found, exit the sub If Len(MyFile) = 0 Then MsgBox "No files were found...", vbExclamation Exit Sub End If 'Loop through each Excel file in the folder Do While Len(MyFile) > 0 'Assign the date/time of the current file to a variable LMD = FileDateTime(MyPath & MyFile) 'If the date/time of the current file is greater than the latest 'recorded date, assign its filename and date/time to variables If LMD > LatestDate Then LatestFile = MyFile LatestDate = LMD End If 'Get the next Excel file from the folder MyFile = Dir Loop 'Open the latest file Workbooks.Open MyPath & LatestFile End Sub 

如果您只想查看文件名以确定“最新”文件,则不必在完整path上调用FileDateTime ,而FileDateTime在文件名上调用以下函数。

您需要对文件名进行一些调整,这与您的问题不完全相同。

 'MyFile053017.xls >> 5/30/2017 Function NewFileDateTime(sFile As String) NewFileDateTime = DateSerial(2000 + Mid(sFile, 11, 2), _ Mid(sFile, 7, 2), _ Mid(sFile, 9, 2)) End Function