Finding files using Dir

  • Thread starter Thread starter farful
  • Start date Start date
F

farful

Hi, I was wondering if someone could show me how, give a directory (n
need for sub directories or hidden files or system files, etc) to ope
the last modified excel file given a partial string (the beginning par
of the filename) using VBA, preferably using the "Dir" function
 
Hi farful,

the code below opens the last modified excel file with a filename like
"ABC...." in folder "C:\Temp\". Instead of the "Dir" function it uses
the FileSystemObject. You may proof me wrong here, but I don't think
it's even possible to retrieve the date and time of the last
modification of a given file using the "Dir" function. To access the
property "DateLastModified" of a given file you need that file as an
object, whereas the "Dir" function returns path and name of files as a
string instead.

Regards,
Ingolf

Sub filesearch()

'--------------------------------
Dim fso As Object
Dim fo As Object
Dim f As Object
Dim LastMod As Date
Dim FilePathName As String
'--------------------------------


Set fso = CreateObject("Scripting.FileSystemObject")
Set fo = fso.GetFolder("C:\Temp\")
For Each f In fo.Files
If Left(f.Name, 3) = "ABC" Then
If f.datelastmodified > LastMod Then
LastMod = f.datelastmodified
FilePathName = f.Path
End If
End If
Next 'f

Workbooks.Open Filename:=FilePathName

End Sub
 
How about this:

Private Sub CommandButton1_Click()
Debug.Print GetOldestModifiedFile("C:")
End Sub

Public Function GetOldestModifiedFile(argFolderToSearch As String, _
Optional argPattern As String =
"*.xls") _
As String
Dim FileName As String
Dim FileDate As Date
Dim OldestDate As Date
Dim OldestFile As String

If Right(argFolderToSearch, 1) <> "\" Then argFolderToSearch =
argFolderToSearch & "\"
OldestFile = ""
OldestDate = 50000

FileName = Dir(argFolderToSearch & argPattern, vbNormal)
Do Until FileName = ""
FileDate = FileDateTime(argFolderToSearch & FileName)
If FileDate < OldestDate Then
OldestDate = FileDate
OldestFile = FileName
End If
FileName = Dir()
Loop
GetOldestModifiedFile = OldestFile

End Function

NickHK
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top