我每周运行3次大型电子表格,基本上汇总了业务交付和其他信息。每次运行该表格时,我都需要转储3或4份接收报告,以查找相关数据。我基本上是在尝试创建一个宏,该宏将打开文件夹中的最新文件,并将数据复制和粘贴到我的活动工作簿中。我无法获得打开文件的代码-我收到一个运行时错误,指出找不到文件/路径,尽管它绝对正确
我使用的代码如下
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条答案
按热度按时间jdzmm42g1#
原因很简单:你从来没有给LMD赋值,所以LMD总是0(这是一个日期的初始值)。因此,LMD永远不会〉LatestDate(也是0),你从来没有给
Myfile
赋值。最后,你试图用你的文件夹名打开一个文件,当然失败了。只需添加
FileDateTime
命令来获取文件日期:提示:学习使用VBA调试器来检查这类问题。我建议观看https://www.youtube.com/watch?v=Um2JwZfwoFI,但你可以找到很多其他资源。