Set objFSO = CreateObject("Scripting.FileSystemObject")
' Define the folder path to find the newest file here:
strSourceFolder = "C:\Temp\Folder1"
' Define the folder path to find the newest file here:
strTargetFolder = "C:\Temp\Folder2"
' Make sure the target folder has a trailing slash
If Right(strTargetFolder, 1) <> "\" Then strTargetFolder = strTargetFolder & "\"
' Here we call the GetNewestFile function, passing the path to the source folder for it to search
strNewestFilePath = GetNewestFile(strSourceFolder)
' Now copy the newest file to the target folder
objFSO.CopyFile strNewestFilePath, strTargetFolder, True
MsgBox strNewestFilePath & " was copied to " & strTargetFolder
Function GetNewestFile(ByVal sPath)
sNewestFile = Null ' init value
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder(sPath)
Set oFiles = oFolder.Files
' enumerate the files in the folder, finding the newest file
For Each oFile In oFiles
On Error Resume Next
If IsNull(sNewestFile) Then
sNewestFile = oFile.Path
dPrevDate = oFile.DateLastModified
ElseIf dPrevDate < oFile.DateLastModified Then
sNewestFile = oFile.Path
dPrevDate = oFile.DateLastModified
End If
On Error Goto 0
Next
If IsNull(sNewestFile) Then sNewestFile = ""
GetNewestFile = sNewestFile
End Function
|