Replace the old file with new file

58 Views Asked by At

The code moves files from one folder to another. However, it stops if a file is already in the destination folder.

If a file with same name comes it should replace it with the new one.

Sub MoveFilesAccordingFileType()
    Dim fso As Scripting.FileSystemObject
    Dim Fl As Scripting.File
    Dim sourceFldr As Scripting.Folder
    Dim DestinationFldr As Scripting.Folder
    Set fso = New FileSystemObject
    Set sourceFldr = fso.GetFolder("E:\Deploy_The_Process\Add Limits")
    Set DestinationFldr = fso.GetFolder("E:\Deploy_The_Process\Archive\Word")
    For Each Fl In sourceFldr.Files
        If (fso.GetExtensionName(Fl.Path) = "docx") Then
            fso.MoveFile Fl.Path, DestinationFldr.Path & "/"
        End If
    Next Fl
End Sub
1

There are 1 best solutions below

0
CLR On BEST ANSWER

You probably just want your loop to have a conditional kill line like so:

    For Each Fl In sourceFldr.Files
        If (fso.GetExtensionName(Fl.Path) = "docx") Then
            If Dir(DestinationFldr.Path & "/" & Fl.Name) <> "" Then Kill DestinationFldr.Path & "/" & Fl.Name
            fso.MoveFile Fl.Path, DestinationFldr.Path & "/"
        End If
    Next Fl