简体   繁体   中英

excel vba macro copy multiple files from folder to folder

I've created this macro in excel that enables a user to copy multiple files from one folder to another. The macros works, it does what it's supposed to do. I just want to add some additional functions to it and I'm not able to make it work. These are the few things that I want to add:

1-check if a file already exists in the destination folder and ask if the user wants to overwrite yes/no. If yes overwrite, If no skip to the next file to be copied.

2-If a file(s) is missing in the source folder the ErrHandler copies the name(s) of the missing file(s) from column A to the M column. The way I did this it works, but it's not how I want it to work. What I want is, if the file name in cell A3, A7, A10 are missing. Those names should be copied to M1, M2, M3 and so on. Instead of copying them to M3, M7, M10

I'm also having 2 other problems:

1-The ErrHandler messagebox it appears more than it should. Once the copy is completed it still shows it 2 more times.

2-The macro it rewrites how the file name is written. For example if the original file name is written in lower case and in a cell I write it in upper case. Once the file is copied it will be written in upper case. I want to keep the original name.

    Dim r As Long
    Dim SourcePath As String
    Dim dstPath As String
    Dim myFile As String

    SourcePath = Range("F1")
    dstPath = Range("F3")

    On Error GoTo ErrHandler

    For r = 1 To 3000
        myFile = Range("A" & r)
        FileCopy SourcePath & "\" & myFile, dstPath & "\" & myFile

        If Range("A" & r) = "" Then 
           Exit For
        End If

    Next r

        MsgBox "The file(s) can found in: " & vbNewLine & dstPath, , "COPY COMPLETED"

ErrHandler:
    MsgBox "Copy error: " & SourcePath & "\" & myFile & vbNewLine & vbNewLine & _
    "File could not be found in the source folder", , "MISSING FILE(S)"

Range("A" & r).Copy Range("M" & r)

Resume Next

End Sub

For the 1st issue, you just need to add an Exit Sub before the ErrHandler: label.
For the second issue, you could try something like (untested):

myFile = dir(SourcePath & "\" & Range("A" & r))
FileCopy SourcePath & "\" & myFile, dstPath & "\" & myFile

This way myFile will contain the original source case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM