Move all files in folder if not already in destination folder

101 Views Asked by At

The below mentioned code moves one file at a time (oldest first) from Source to Destination.

I would like to add a loop so if there are 100 files in a source folder it could move the files one by one automatically.

Also if the file already exists in the destination folder it should skip that file and should not stop the process.

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
    
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
0

There are 0 best solutions below