Home » excel » excel – Copy a file from a filepath to another

excel – Copy a file from a filepath to another

Posted by: admin May 14, 2020 Leave a comment

Questions:

The below code is trying to copy a file from a folder to a another directory.

It is not able to find the file even though it’s there.

Sub copyFiles()

Dim fldrname As String, fldrpath As String, sFileType As String
Dim sSourcePath As String, Destination As String
Dim sFile As String
Dim fso As Object, fFolder As Object, fFile As Object

Set fso = CreateObject("scripting.filesystemobject")
sSourcePath = "\oak\data\Placeholder\APP\VMP0\sxv0_out" '
sFile = "Placeholder.csv"
fldrpath = "W:\Placeholder18. Oct\"

Set fFolder = fso.GetFolder(sSourcePath)

'For Each fFile In fFolder.files
If Not fso.FileExists(fFolder & sFile) Then
    MsgBox "Specified File Not Found", vbInformation, "Not Found"

    'Copying If the Same File is Not Located in the Destination Folder
    ElseIf Not fso.FileExists(fldrpath & sFile) Then
        fso.Copyfile (fFolder & sFile), fldrpath, True
        MsgBox "Specified File Copied Successfully", vbInformation, "Done!"
    Else
        MsgBox "Specified File Already Exists In The Destination Folder", vbExclamation, "File Already Exists"
End If

End Sub
How to&Answers:

I prefer using DIR over FileSystemObject as former being a native function. Here is the code to copy file from one folder to another. You can also loop through all files using DIR if needed.

Option Explicit

Sub CopyFiles()

    Dim fldrpath As String
    Dim sSourcePath As String
    Dim sFile As String, source_file As String


    sSourcePath = "\oak\data\Placeholder\APP\VMP0\sxv0_out"
    sFile = "Placeholder.csv"
    fldrpath = "W:\Placeholder18. Oct\"

    source_file = Dir(sSourcePath & "\" & sFile)

    If Trim(source_file) <> vbNullString Then
        If Dir(fldrpath, vbDirectory) = vbNullString Then MkDir fldrpath
        FileCopy sSourcePath & "\" & sFile, fldrpath & sFile
        MsgBox "Specified File Copied Successfully", vbInformation, "Done!"
        Else
            MsgBox "Specified File Not Found", vbInformation, "Not Found"
        End If


End Sub