Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Identify newest file in a subdirectory 2

Status
Not open for further replies.

edmac

Programmer
May 2, 2001
30
US
I need help on the following: I need an example of a code to determine wich is the newest (more recent) file in a given sibdirectory and then copy such file to another directory. I need this for security purposes. Please help, I'm really new to Visual Basic !!!! Thanks - Ed.
 
Hi,
Create a command button and try this. Modify as needbe.

Private Sub cmdGetNewestFile_Click()
Dim fs, f
Dim DestPath As String
Dim FName As String

FName = GetNewestFile("C:\UTILS")
DestPath = "C:\"
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFile("C:\UTILS\" & FName)
f.Copy (DestPath & FName)
End Sub

Function GetNewestFile(ByVal Folderspec As String) As String
'This function returns the filename with the latest lastmodifed date in the passed folder.
'If there is more than file with the same date then the last file checked will be returned.
On Error GoTo GetNewestFile_Err

Dim fs, f, fl, fc
Dim NewestDate As Date
Dim NewestFile As String

NewestFile = ""
NewestDate = "01/01/1000"
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFolder(Folderspec)
Set fc = f.Files
For Each fl In fc
If fl.datecreated > NewestDate Then
NewestDate = fl.datecreated
NewestFile = fl.Name
End If
Next fl
GetNewestFile = NewestFile

GetNewestFile_Exi: Exit Function
GetNewestFile_Err:
MsgBox Error$, vbExclamation + vbOKOnly, "GetNewestFile()"
Resume GetNewestFile_Exi
End Function
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top