excelvbafilesystemobject

Replace the old file with new file


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

Solution

  • 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