excelvba

Copy a file and a folders to location based on excel list


r/excel - Copy a file and a folders to location based on excel list I am trying to copy a list of files and folders based on the source column in a Excel to a new location. I have an excel list of the files and folders that need to be copied and keep partial original path (See screenshot) desire outcome.

enter image description here

I got this far but I keep getting an error -

Run-time error 52
Bad file name or number

here is my code:

Sub CopyFilesAndFolders()
    Dim wb As Workbook
    Dim ws As Worksheet
    Dim sourceFolder As String
    Dim destFolder As String
    Dim fileName As String
    Dim folderName As String
    Dim destinationFolder As String
    Dim sourcePath As String
    Dim destPath As String
    Dim i As Long
    

    ' Define the source folder
    sourceFolder = "C:\Users\pc50\Desktop\Source"

    ' Open the Excel file containing the list
    Set wb = Workbooks.Open("C:\Users\pc50\Desktop\FF2.xlsx")
    Set ws = wb.Sheets("Sheet1") ' Change "Sheet1" to your sheet name

    ' Loop through the rows in the Excel sheet
    For i = 2 To ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
        ' Read values from Excel sheet
        fileName = ws.Cells(i, 1).Value
        folderName = ws.Cells(i, 2).Value
        destinationFolder = ws.Cells(i, 3).Value

        ' Construct source and destination paths
        sourcePath = sourceFolder &  fileName
        destPath = destinationFolder

        ' Check if destination folder exists, create if not
        Debug.Print sourcePath & vbLf & destPath
        If Dir(destPath, vbDirectory) = "" Then
            MkDir destPath
        End If

        ' Copy file to destination
        FileCopy sourcePath, destPath

    Next i

    ' Close the Excel file
    wb.Close SaveChanges:=False
End Sub

Solution

  • This should work assuming all files exist and only the last level of the destination folder path might be missing:

    Sub CopyFilesAndFolders()
        Dim wb As Workbook, ws As Worksheet
        Dim sourceFolder As String, destFolder As String, fileName As String
        Dim i As Long
    
        Set wb = Workbooks.Open("C:\Users\pc50\Desktop\FF2.xlsx")
        Set ws = wb.Sheets("Sheet1") ' Change "Sheet1" to your sheet name
    
        ' Loop through the rows in the Excel sheet
        For i = 2 To ws.Cells(ws.Rows.Count, 1).End(xlUp).row
            
            fileName = ws.Cells(i, 1).Value       ' Read values from Excel sheet
            sourceFolder = ws.Cells(i, 2).Value   ' folder paths are assumed to end in \
            destFolder = ws.Cells(i, 3).Value
    
            If Dir(destFolder, vbDirectory) = "" Then MkDir destFolder
            
            FileCopy sourceFolder & fileName, destFolder & fileName
    
        Next i
        
        wb.Close SaveChanges:=False ' Close the Excel file
    End Sub