我每周運行 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
uj5u.com熱心網友回復:
原因很簡單:您永遠不會為 LMD 分配任何內容,因此 LMD 始終為 0(即日期的初始值)。因此,LMD 永遠不會 > LatestDate(也是 0),您永遠不會為Myfile. 最后,您嘗試使用您的檔案夾名稱打開一個檔案,這當然會失敗。
只需添加FileDateTime命令以獲取檔案日期:
LMD = FileDateTime(Mypath & Myfile)
If LMD > LatestDate Then
LatestFile = Myfile
LatestDate = LMD
End If
提示:學習使用 VBA 除錯器來檢查此類問題。我建議觀看https://www.youtube.com/watch?v=Um2JwZfwoFI,但您可以找到很多其他資源。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/530989.html
標籤:擅长vba
上一篇:腳本太慢了。如何處理大檔案?
下一篇:在Excel中復制到上面的行
