我每周更新三次电子表格,总结业务交付和其他信息。
工作表要求我每次都要转储三到四份入院报告,以查找相关数据。我想打开文件夹中最近的文件,并将数据复制到我的活动工作簿中。
我无法打开文件。我收到一个运行时错误,指出找不到文件/路径。
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 = "C:\Users\Documents"
'Make sure that the path ends in a backslash
If Right(Mypath, 1) <> "\" Then Mypath = Mypath & "\"
'Get the lfirst excel file from the folder
Myfile = Dir(Mypath & "*xlsx", 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 folder
Do While Len(Myfile) > 0
'If 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
1条答案
按热度按时间hmmo2u0o1#
原因很简单:你从来没有给LMD赋值,所以LMD总是0(这是一个日期的初始值)。因此,LMD永远不会〉LatestDate(也是0),你从来没有给
Myfile
赋值。最后,你试图打开一个文件夹名的文件,当然失败了。只需添加
FileDateTime
命令来获取文件日期:提示:学习使用VBA调试器来检查这类问题。我建议观看https://www.youtube.com/watch?v=Um2JwZfwoFI,但你可以找到很多其他的资源。