Struggling to open most recent .xls in specified folder. File Not Found error

风格不统一 提交于 2019-12-13 05:26:05

问题


This is my first post so I apologize if I fail to give enough information. I'll do my best.

I am attempting to scan through a specific folder and open the most recently titled Excel file. The files are named '9 1 13' and '9 2 13' ect. My sub correctly steers itself to the right folder and identifies the most recent file. However, when I attempt to open it, I get a runtime error 1004.

File '9 2 13.xlsx' could not be found, check spelling....

It clearly has found the right file and path to it, so why can't VBA open it? My current sub is below. Before anyone asks, the file path '\\Hsrkdfs\hsdata\rk\grp06....' is because I am pulling from a network where everyone's network access isn't mapped the same. Some access this folder from the G: drive, others the R:, and this macro must be functional from all computers. The error occurs on the 'Workbooks.Open strFilename line.

Sub GetMostRecentFile()

Dim FileSys As FileSystemObject
Dim objFile As File
Dim myFolder
Dim strFilename As String
Dim dteFile As Date

'set path for files - CHANGE FOR YOUR APPROPRIATE FOLDER
Const myDir As String = "\\Hsrkdfs\hsdata\rk\grp06\Rockford Repair Station   Quality\DELIVERY\Daily Status report - commercial"


'set up filesys objects
Set FileSys = New FileSystemObject
Set myFolder = FileSys.GetFolder(myDir)


'loop through each file and get date last modified. If largest date then store Filename
dteFile = DateSerial(1900, 1, 1)
For Each objFile In myFolder.Files
    If objFile.DateLastModified > dteFile Then
        dteFile = objFile.DateLastModified
        strFilename = objFile.Name
    End If
Next objFile
Workbooks.Open strFilename

Set FileSys = Nothing
Set myFolder = Nothing

End Sub

回答1:


Try using .Path which returns the full path, rather than .Name, which only returns the name and extension of the file.

strFilename = objFile.Path


来源:https://stackoverflow.com/questions/18708532/struggling-to-open-most-recent-xls-in-specified-folder-file-not-found-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!