prashant089
New Member
- Joined
- Jan 23, 2012
- Messages
- 10
Dear Friends
I am trying to open the most recent text file through excel macro but there is this "Run-time error '1004' " message pops up and says that it can not find the file though it is displaying the name of file. I am slightly new to VBA and I have copied this formula from another online help posting.
Can someone review the codes and let me know how to correct it. I am working on Windows 7 and Excel 2010 version.
Thanks in advance.
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 folder
Const myDir As String = "C:\Users\Admin\Documents\CDR Reports\Jan2012\TXT Files"
'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
Prashant Paul
I am trying to open the most recent text file through excel macro but there is this "Run-time error '1004' " message pops up and says that it can not find the file though it is displaying the name of file. I am slightly new to VBA and I have copied this formula from another online help posting.
Can someone review the codes and let me know how to correct it. I am working on Windows 7 and Excel 2010 version.
Thanks in advance.
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 folder
Const myDir As String = "C:\Users\Admin\Documents\CDR Reports\Jan2012\TXT Files"
'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
Prashant Paul