Tip: Other languages are Google-Translated. You can visit the English version of this link.
Log in
x
or
x
x
Register
x

or

How to copy or move files from one folder to another based on a list in Excel? 

If you have a list of file names in a column in a worksheet, and the files locate in a folder in your computor. But, now, you need to move or copy these files which names are listed into the worksheet from their original folder to another one as following screenshot shown. How could you finish this task as quickly as you can in Excel?

Copy or move files from one folder to another based on a list in Excel with VBA code


Copy or move files from one folder to another based on a list in Excel with VBA code


To move the files from one folder to another based on a list of files names, the following VBA code may do you a favor, please do as this:

1. Hold down the Alt + F11 keys in Excel, and it opens the Microsoft Visual Basic for Applications window.

2. Click Insert > Module, and paste the following VBA code in the Module Window.

VBA code: Move files from one folder to another based on a list in Excel

Sub movefiles()
'Updateby Extendoffice
    Dim xRg As Range, xCell As Range
    Dim xSFileDlg As FileDialog, xDFileDlg As FileDialog
    Dim xSPathStr As Variant, xDPathStr As Variant
    Dim xVal As String
    On Error Resume Next
    Set xRg = Application.InputBox("Please select the file names:", "KuTools For Excel", ActiveWindow.RangeSelection.Address, , , , , 8)
    If xRg Is Nothing Then Exit Sub
    Set xSFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
    xSFileDlg.Title = " Please select the original folder:"
    If xSFileDlg.Show <> -1 Then Exit Sub
    xSPathStr = xSFileDlg.SelectedItems.Item(1) & "\"
    Set xDFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
    xDFileDlg.Title = " Please select the destination folder:"
    If xDFileDlg.Show <> -1 Then Exit Sub
    xDPathStr = xDFileDlg.SelectedItems.Item(1) & "\"
    For Each xCell In xRg
        xVal = xCell.Value
        If TypeName(xVal) = "String" And xVal <> "" Then
            FileCopy xSPathStr & xVal, xDPathStr & xVal
            Kill xSPathStr & xVal
        End If
    Next
End Sub

3. And then press F5 key to run this code, and a prompt box will pop out to remind you selecting the cells which contain the file names, see screenshot:

4. Then click OK button, and in the popped out window, please select the folder which contains the files that you want to move from, see screenshot:

5. And then click OK, go on selecting the destination folder where you want to locate the files in another popped out window, see screenshot:

6. Finally, click OK to close the window, and now, the files have been moved into another folder you specified based on the file names in worksheet list, see screenshot:

Note: If you just want to copy the files to another folder, but keep the original files, please apply the below VBA code:

VBA code: Copy files from one folder to another based on a list in Excel

Sub copyfiles()
'Updateby Extendoffice
    Dim xRg As Range, xCell As Range
    Dim xSFileDlg As FileDialog, xDFileDlg As FileDialog
    Dim xSPathStr As Variant, xDPathStr As Variant
    Dim xVal As String
    On Error Resume Next
    Set xRg = Application.InputBox("Please select the file names:", "KuTools For Excel", ActiveWindow.RangeSelection.Address, , , , , 8)
    If xRg Is Nothing Then Exit Sub
    Set xSFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
    xSFileDlg.Title = "Please select the original folder:"
    If xSFileDlg.Show <> -1 Then Exit Sub
    xSPathStr = xSFileDlg.SelectedItems.Item(1) & "\"
    Set xDFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
    xDFileDlg.Title = "Please select the destination folder:"
    If xDFileDlg.Show <> -1 Then Exit Sub
    xDPathStr = xDFileDlg.SelectedItems.Item(1) & "\"
    For Each xCell In xRg
        xVal = xCell.Value
        If TypeName(xVal) = "String" And xVal <> "" Then
            FileCopy xSPathStr & xVal, xDPathStr & xVal
        End If
    Next
End Sub

Kutools for Excel Solves Most of Your Problems, and Increases Your Productivity by 80%

  • Reuse: Quickly insert complex formulas, charts and anything that you have used before; Encrypt Cells with password; Create Mailing List and send emails...
  • Super Formula Bar (easily edit multiple lines of text and formula); Reading Layout (easily read and edit large numbers of cells); Paste to Filtered Range...
  • Merge Cells/Rows/Columns without losing Data; Split Cells Content; Combine Duplicate Rows/Columns... Prevent Duplicate Cells; Compare Ranges...
  • Select Duplicate or Unique Rows; Select Blank Rows (all cells are empty); Super Find and Fuzzy Find in Many Workbooks; Random Select...
  • Exact Copy Multiple Cells without changing formula reference; Auto Create References to Multiple Sheets; Insert Bullets, Check Boxes and more...
  • Extract Text, Add Text, Remove by Position, Remove Space; Create and Print Paging Subtotals; Convert Between Cells Content and Comments...
  • Super Filter (save and apply filter schemes to other sheets); Advanced Sort by month/week/day, frequency and more; Special Filter by bold, italic...
  • Combine Workbooks and WorkSheets; Merge Tables based on key columns; Split Data into Multiple Sheets; Batch Convert xls, xlsx and PDF...
  • More than 300 powerful features. Supports Office/Excel 2007-2019 and 365. Supports all languages. Easy deploying in your enterprise or organization. Full features 30-day free trial.
kte tab 201905

Office Tab Brings Tabbed interface to Office, and Make Your Work Much Easier

  • Enable tabbed editing and reading in Word, Excel, PowerPoint, Publisher, Access, Visio and Project.
  • Open and create multiple documents in new tabs of the same window, rather than in new windows.
  • Increases your productivity by 50%, and reduces hundreds of mouse clicks for you every day!
officetab bottom
Say something here...
symbols left.
You are guest ( Sign Up? )
or post as a guest, but your post won't be published automatically.
Loading comment... The comment will be refreshed after 00:00.
  • To post as a guest, your comment is unpublished.
    Nasr · 2 months ago
    Any update of how to search on folder and subfolders
    • To post as a guest, your comment is unpublished.
      skyyang · 1 months ago
      Hi, Nasr,
      To move files from folder and subfolders based on cell values, please apply the below VBA code:
      Please try, hope it can help you!

      Sub movefiles()
      'Updateby Extendoffice
      Dim xRg As Range, xCell As Range
      Dim xSFileDlg As FileDialog, xDFileDlg As FileDialog
      Dim xSPathStr As Variant, xDPathStr As Variant
      Dim xVal As String
      Dim fso As Object, folder1 As Object
      ' On Error Resume Next
      Set xRg = Application.InputBox("Please select the file names:", "KuTools For Excel", ActiveWindow.RangeSelection.Address, , , , , 8)
      If xRg Is Nothing Then Exit Sub
      Set xSFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
      xSFileDlg.Title = " Please select the original folder:"
      If xSFileDlg.Show <> -1 Then Exit Sub
      xSPathStr = xSFileDlg.SelectedItems.Item(1) & "\"
      Set xDFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
      xDFileDlg.Title = " Please select the destination folder:"
      If xDFileDlg.Show <> -1 Then Exit Sub
      xDPathStr = xDFileDlg.SelectedItems.Item(1) & "\"
      Call sMoveFiles(xRg, xSPathStr, xDPathStr)
      End Sub

      Sub sMoveFiles(xRg As Range, xSPathStr As Variant, xDPathStr As Variant)
      Dim xCell As Range
      Dim xVal As String
      Dim xFolder As Object
      Dim fso As Object
      Dim xF As Object
      Dim xStr As String
      Dim xFS As Object
      Dim xI As Integer
      On Error Resume Next
      If Dir(xDPathStr, vbDirectory) = "" Then
      MkDir (xDPathStr)
      End If
      For xI = 1 To xRg.Count
      Set xCell = xRg.Item(xI)
      xVal = xCell.Value
      If TypeName(xVal) = "String" And Not (xVal = "") Then
      On Error GoTo E1
      If Dir(xSPathStr & xVal, 16) <> Empty Then
      FileCopy xSPathStr & xVal, xDPathStr & xVal
      Kill xSPathStr & xVal
      End If
      End If
      E1:
      Next xI
      On Error Resume Next
      Set fso = CreateObject("Scripting.FileSystemObject")
      Set xFS = fso.GetFolder(xSPathStr)
      For Each xF In xFS.SubFolders
      xStr = xDPathStr & "\" & xF.Name ' Replace(xF.ShortPath, xSPathStr, xDPathStr)
      Call sMoveFiles(xRg, xF.ShortPath & "\", xStr & "\")
      If (CreateObject("scripting.FileSystemObject").GetFolder(xStr).Files.Count = 0) _
      And (CreateObject("scripting.FileSystemObject").GetFolder(xStr).SubFolders.Count = 0) Then
      RmDir xStr
      End If
      Next
      End Sub
      • To post as a guest, your comment is unpublished.
        Nasr · 1 months ago
        That's perfect thank you
        but what about if I just wanted to copy files not moving it from subfolders only without the need of creating subfolders in the destination folder
        ie
        source folder X:\\parent
        inside parent is subfolders test1(file A), test2(file B) and test3(file C)
        then destination folder is "Y:\\destination" has all 3 files A, B, C without the subfolders

        Thank you very much
        • To post as a guest, your comment is unpublished.
          Mike · 5 days ago
          Hi Nasr, did you figure out how to do this? I am looking at a similar need at the moment.

          Copying a selection of files from various subfolders to a single folder
          • To post as a guest, your comment is unpublished.
            Nasr · 7 hours ago
            Hi Mike
            I kind of did BUT indirectly, so what I did is modify the code to copy the files not move them with the subfolder
            then with CMD file move the file from subfolders to the main folder then delete the empty subfolder
            this is what I did

            Sub Copyfiles()
            'Updateby Extendoffice
            Dim xRg As Range, xCell As Range
            Dim xSFileDlg As FileDialog, xDFileDlg As FileDialog
            Dim xSPathStr As Variant, xDPathStr As Variant
            Dim xVal As String
            Dim fso As Object, folder1 As Object
            ' On Error Resume Next
            Set xRg = Application.InputBox("Please select the file names:", "KuTools For Excel", ActiveWindow.RangeSelection.Address, , , , , 8)
            If xRg Is Nothing Then Exit Sub
            Set xSFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
            xSFileDlg.Title = " Please select the original folder:"
            If xSFileDlg.Show <> -1 Then Exit Sub
            xSPathStr = xSFileDlg.SelectedItems.Item(1) & "\"
            Set xDFileDlg = Application.FileDialog(msoFileDialogFolderPicker)
            xDFileDlg.Title = " Please select the destination folder:"
            If xDFileDlg.Show <> -1 Then Exit Sub
            xDPathStr = xDFileDlg.SelectedItems.Item(1) & "\"
            Call sCopyFiles(xRg, xSPathStr, xDPathStr)
            End Sub

            Sub sCopyFiles(xRg As Range, xSPathStr As Variant, xDPathStr As Variant)
            Dim xCell As Range
            Dim xVal As String
            Dim xFolder As Object
            Dim fso As Object
            Dim xF As Object
            Dim xStr As String
            Dim xFS As Object
            Dim xI As Integer
            On Error Resume Next
            If Dir(xDPathStr, vbDirectory) = "" Then
            MkDir (xDPathStr)
            End If
            For xI = 1 To xRg.Count
            Set xCell = xRg.Item(xI)
            xVal = xCell.Value
            If TypeName(xVal) = "String" And Not (xVal = "") Then
            On Error GoTo E1
            If Dir(xSPathStr & xVal, 16) <> Empty Then
            FileCopy xSPathStr & xVal, xDPathStr & xVal
            End If
            End If
            E1:
            Next xI
            On Error Resume Next
            Set fso = CreateObject("Scripting.FileSystemObject")
            Set xFS = fso.GetFolder(xSPathStr)
            For Each xF In xFS.SubFolders
            xStr = xDPathStr & "\" & xF.Name ' Replace(xF.ShortPath, xSPathStr, xDPathStr)
            Call sCopyFiles(xRg, xF.ShortPath & "\", xStr & "\")
            If (CreateObject("scripting.FileSystemObject").GetFolder(xStr).Files.Count = 0) _
            And (CreateObject("scripting.FileSystemObject").GetFolder(xStr).SubFolders.Count = 0) Then
            RmDir xStr
            End If
            Next
            End Sub



            then copy the following lines to a new notepad then save it as cmd call it whatever

            for /r %%a IN (*.*) do (
            move /y "%%a" "%cd%"
            )
            for /f "delims=" %%d in ('dir /s /b /ad ^| sort /r') do rd "%%d"



            make sure to copy the code as is 4 lines
            hope that help
            • To post as a guest, your comment is unpublished.
              Nasr · 7 hours ago
              make sure to put the cmd file in the same folder that you copy the files and subfolders to then double click it
  • To post as a guest, your comment is unpublished.
    ADOLFO · 3 months ago
    buenas noches, alguien sabe que tengo que modificar para que me mueva carpetas y no solo archivos?
  • To post as a guest, your comment is unpublished.
    jonathan · 4 months ago
    thanks so much !
  • To post as a guest, your comment is unpublished.
    Michael · 4 months ago
    Has anyone figured out how to copy files that are located in multiple subfolders of the main directory, and paste into another folder directory? Also does this transfer method only work for folders on the C drive? I am trying to copy files from our directory that includes multiple subfolders where several files are stored located in Microsoft Sharepoint, to a folder on my C drive.

    Any help would be much appreciated!
  • To post as a guest, your comment is unpublished.
    julien · 5 months ago
    hi do you know how to search also on the subfolder ?
  • To post as a guest, your comment is unpublished.
    Technically Specific · 7 months ago
    Works great - thank you! However-->>>Can this be adjusted to use a PARTIAL FILE NAME? If so, can you help show how?
    In other words, if file name on the Excel sheet list of filenames is: OW4234TR_J19031.txt (I'd like it to only look at last 5 chars "19031" which is a Julian Date and move a range of files... (anything with a Julian Date of 19092 thru 19120) into the March folder.. The ultimate over-arching task is to locate any files that have Julian dates for March and put those in the Fiscal March Folder "06-Mar" , April into the April folder "07-Apr" and so on...so Fiscal reconciliations by month can then take place.. TIA for any help anyone can offer to expedite this time consuming hunt and picking process. =-)
  • To post as a guest, your comment is unpublished.
    Fer · 8 months ago
    en el codigo que copia ¿como puedo colorear el nombre de la lista que no encuentre?
  • To post as a guest, your comment is unpublished.
    Johnette · 9 months ago
    I cannot get either version to work in Windows 10.


    Argggg
  • To post as a guest, your comment is unpublished.
    Andy · 1 years ago
    Any tips on how to modify the code to add a wide card? I have an archive of hundreds of PDF files that are 10 digit numbers and revision level (XXXXXXXXXX_REVA). I can export a list of file names very easily from our ERP system, but the list is missing the revision and file extension. Is there a way to add wild cards into the program to ignore everything BUT the 10 digit number?
  • To post as a guest, your comment is unpublished.
    PWD · 1 years ago
    Hello,
    how to make this code copy files from subfolders?
  • To post as a guest, your comment is unpublished.
    Pr · 1 years ago
    Hi Guys,

    How I need to change '' If TypeName(xVal) = "String" And xVal <> "" Then '' to move files based on partial file name.


    Thanks in advance,
    Best regards, P
    • To post as a guest, your comment is unpublished.
      Technically Specific · 7 months ago
      Did you ever find out HOW to use a PARTIAL FILE NAME? I need that as well...
      In other words, if file name on the Excel sheet list is: OW4234TR_J19031.txt (I'd like it to only look at last 5 chars "19031" which is a Julian Date and move a range of files... anything with a Julian Date of 19031 thru 19075..
      • To post as a guest, your comment is unpublished.
        eric · 2 months ago
        I also would require the partial file name vba modification. Did you ever get a response?
  • To post as a guest, your comment is unpublished.
    Sidney · 1 years ago
    Você não tem noção de como me ajudou com esse script... Muito bom!!! Obrigado!!!
  • To post as a guest, your comment is unpublished.
    Robinson · 1 years ago
    Obrigado!!!!
  • To post as a guest, your comment is unpublished.
    Alisson · 1 years ago
    Era exatamente isso que eu precisava!!!

    Muito Obrigado!!!!
  • To post as a guest, your comment is unpublished.
    Raki · 1 years ago
    Hi, In the source folder, I wish to set it as a constant from a cell, for example the path entered in a particular cell, like A1, should be treated as the source folder. How to do this?
  • To post as a guest, your comment is unpublished.
    madhan · 1 years ago
    It is the nice macro.Real helpful for me. but I need some update macro.this used to copy the files from single folder to another folder. we need copy files from folder and subfolder to another folder.