Thank you Dear Friends, because of you i am able to get the code from below mentioned link, now i have two codes mentioned below.
first code provides the information of file date modified and it successfully working.
second code basically moves the files from one folder to another. Dear Experts can anyone please merge these 2 codes together so that it should first check the oldest modified time and then move it accordingly.? i hope question is clear. however, please also help to include a loop in it.
Sub test()
Dim FSO As Object
Dim fol As Object
Dim fil As Object
Dim temp As Date
Set FSO = CreateObject("Scripting.FileSystemObject")
Set fol = FSO.GetFolder("E:\Source")
For Each fil In fol.Files
temp = fil.DateLastModified
Next fil
MsgBox temp
End Sub
This is the second code
Sub FSOMoveAllFiles()
Dim FSO As New FileSystemObject
Dim FromPath As String
Dim ToPath As String
Dim FileInFromFolder As Object
FromPath = "E:\Source\"
ToPath = "E:\Destination\"
Set FSO = CreateObject("Scripting.FileSystemObject")
For Each FileInFromFolder In FSO.GetFolder(FromPath).Files
FileInFromFolder.Move ToPath
Next FileInFromFolder
End Sub
Best regards
CodePudding user response:
Please, test the next function, able to return the oldest file (according to its creation time):
Function OldestFile(strFold As String) As String
Dim FSO As Object, Folder As Object, File As Object, oldF As String
Dim lastFile As Date: lastFile = Now
Set FSO = CreateObject("Scripting.FileSystemObject")
Set Folder = FSO.GetFolder(strFold)
For Each File In Folder.files
If File.DateCreated < lastFile Then
lastFile = File.DateCreated: oldF = File.name
End If
Next
OldestFile = oldF
End Function
If you need last modified file you should replace File.DateCreated
with File.Datelastmodified
.
It should be called from your code in the next way:
Sub MoveOldestFile()
Dim FromPath As String, ToPath As String, fileName As String
FromPath = "E:\Source\"
ToPath = "E:\Destination\"
fileName = OldestFile(FromPath)
If Dir(ToPath & fileName) = "" Then
Name FromPath & fileName As ToPath & fileName
Else
MsgBox "File """ & fileName & """ already moved..."
End If
End Sub
Each time when the above code is run, moves the oldest file to "ToPath" folder.
Please, send some feedback after testing it.