我从网上提取了一些代码,打开文件夹中的最新文件,这似乎运作良好。然而,在代码的后面,我添加了另一行来设置相同的,最近打开的文件。在尝试此操作时,Workbook subscipt超出了范围,我认为它与语法有关?可能需要在工作簿名称中包含其他引号,任何想法?
'路径'和' latestFile'变量似乎正在正确阅读
Dim path$, file$, latestFile$
Dim LatestDate As Date, LMD As Date
Dim D As worksheet, dash As worksheet
'open latest file
path = "R:\Dept\"
If Right(path, 1) <> "\" Then path = path & "\"
file = Dir(path & "*.xls", vbNormal)
If Len(file) = 0 Then
MsgBox "No files were found in the folder", vbExclamation
End If
Do While Len(file) > 0
LMD = FileDateTime(path & file)
If LMD > LatestDate Then
latestFile = file
LatestDate = LMD
End If
file = Dir
Loop
Application.DisplayAlerts = False
Workbooks.Open path & latestFile
Application.DisplayAlerts = True
Set dash = Workbooks("dashboard.xlsm").Worksheets("D data")
Set D = Workbooks(path & latestFile).Worksheets("D Data") 'error here
答案 0 :(得分:0)
只需使用名称:
Set D = Workbooks(latestFile).Worksheets("D Data")
但要做得更清洁:
Application.DisplayAlerts = False
Set D = Workbooks.Open(path & latestFile).Worksheets("D Data") '<< edit
Application.DisplayAlerts = True