excel vba - copy file from one folder to another but if file exists do not overwrite?

10,586

Solution 1

Simplifying your paths a bit for clarity:

Set fs = CreateObject("Scripting.FileSystemObject")
If Not fs.FileExists("\\path\to\destination" & stuff & "\audit.xls") Then
    FileCopy "\\path\to\source\audit.xls", "\\path\to\destination\" & stuff & "\audit.xls"
End If

Solution 2

Really old thread but apparently the VBA FileCopy statement does not support the boolean parameter described in Kunal's answer (https://docs.microsoft.com/it-it/office/vba/language/reference/user-interface-help/filecopy-statement). On the other hand, the CopyFile method of the Scripting.FileSystemObject does (https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/copyfile-method).

FileSystemObject.CopyFile "c:\mydocuments\letters\file.doc", "c:\tempfolder\", True

Solution 3

FileCopy (sourceString, DestinationString, Boolean) Set Boolean to TRUE if destination can be overwritten, by default it is false.

Share:
10,586
james tanner
Author by

james tanner

Updated on June 05, 2022

Comments

  • james tanner
    james tanner almost 2 years

    Can someone please show me a way of copying a file from one folder to another using vba but with a condition to say if file already exists do not overwrite?

    here is my code:

    If Target.Column = Range("BL1").Column And Target.Row > 14 Then
      FileCopy "\\UKSH000-FILE06\purchasing\New_Supplier_Set_Ups_&_Audits\assets\audit.xls", "\\UKSH000-FILE06\purchasing\New_Supplier_Set_Ups_&_Audits\ATTACHMENTS\" & Range("B" & ActiveCell.Row) & "\audit.xls"
     End If