Copy and move file

I have listed of files name in column A, i know the parent(Source) folder, but i don’t know which sub-folder have my file. In main folder there is lot of sub folder, so search all sub folder if file name available that file copy and move to destination folder.

Code Explanation: First it ask source folder location destination, i choose parent folder(parent folder have lot of sub folder) and then destination folder then it recursively search folder which folder have exact file name if its available any folder it copy and move to destination folder. But this code gone wrong while running. Please anyone solve this issue.

Sub copy_and_move_selectedfiles_recursive()
    On Error Resume Next
    Dim sourceFolderDialog As FileDialog
    Dim destinationFolderDialog As FileDialog
    Dim sourceFolderPath As String
    Dim destinationFolderPath As String
    Dim FSO As Object
    Dim ws As Worksheet
    Dim lastRow As Long
    Dim c As Range
    ' Select source folder
    Set sourceFolderDialog = Application.FileDialog(msoFileDialogFolderPicker)
    With sourceFolderDialog
        .Title = "Select Source Folder"
        .AllowMultiSelect = False
        If .Show = -1 Then
            sourceFolderPath = .SelectedItems(1) & ""
        Else
            Exit Sub
        End If
    End With
    ' Select destination folder
    Set destinationFolderDialog = Application.FileDialog(msoFileDialogFolderPicker)
    With destinationFolderDialog
        .Title = "Select Destination Folder"
        .AllowMultiSelect = False
        If .Show = -1 Then
            destinationFolderPath = .SelectedItems(1) & ""
        Else
            Exit Sub
        End If
    End With
    ' Initialize FileSystemObject
    Set FSO = CreateObject("Scripting.FileSystemObject")
    ' Set worksheet
    Set ws = ThisWorkbook.Sheets("Sheet1") ' Change the sheet name as needed
    ' Find the last row with data in column C
    lastRow = ws.Cells(ws.Rows.Count, 3).End(xlUp).Row
    ' Loop through each cell in column C from C3 to the last row
    For Each c In ws.Range("C3:C" & lastRow)
        ' Search for the file in source folder and its subfolders
        If FileExistsRecursive(sourceFolderPath, c.Value) Then
            ' File exists in source folder or its subfolders
            c.Offset(0, 1).Value = "Moved"
            ' Move the file to destination folder
            FSO.MoveFile sourceFolderPath & c.Value, destinationFolderPath & c.Value
        Else
            ' File not found in source folder or its subfolders
            c.Offset(0, 1).Value = "Not Found"
        End If
    Next c
    ' Clean up
    Set FSO = Nothing
    ' Show completion message
    MsgBox "Process Completed"
End Sub
 
Function FileExistsRecursive(ByVal folderPath As String, ByVal fileName As String) As Boolean
    Dim FSO As Object
    Dim objFolder As Object
    Dim objFile As Object
    Dim found As Boolean
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set objFolder = FSO.GetFolder(folderPath)
    ' Check if the file exists in the current folder
    For Each objFile In objFolder.Files
        If objFile.Name = fileName Then
            Set FSO = Nothing
            FileExistsRecursive = True
            Exit Function
        End If
    Next objFile
    ' Recursively search through subfolders
    For Each objFolder In objFolder.SubFolders
        If FileExistsRecursive(objFolder.Path, fileName) Then
            Set FSO = Nothing
            FileExistsRecursive = True
            Exit Function
        End If
    Next objFolder
    ' File not found
    Set FSO = Nothing
    FileExistsRecursive = False
End Function

6

Try the following changes and take care of the limitations below:

Change in the Sub:

Define a module level variable on the top of the module

Dim foundfile As String

Add this line to the Sub procedure

        If FileExistsRecursive(sourceFolderPath, c.value) Then
            ' File exists in source folder or its subfolders
            c.Offset(0, 1).value = "Moved"
            ' Move the file to destination folder
            FSO.MoveFile foundfile, destinationFolderPath & c.value
            foundfile = ""             '------add this line
        Else
            ' File not found in source folder or its subfolders
            c.Offset(0, 1).value = "Not Found"
        End If

Do the following changes in the Function

Function FileExistsRecursive(ByVal folderPath As String, ByVal fileName As String) As Boolean
    Dim FSO As Object
    Dim objFolder As Object
    Dim objSubFolder As Object   '--------------added
    Dim objFile As Object
    Dim found As Boolean
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set objFolder = FSO.GetFolder(folderPath)
    ' Check if the file exists in the current folder
    'If InStr(1, folderPath, "appda", vbTextCompare) > 0 Then Debug.Print folderPath
    'Debug.Print folderPath
    For Each objFile In objFolder.Files
        If objFile.Name = fileName Then
            Set FSO = Nothing
            foundfile = objFile.Path    '----------------added
            FileExistsRecursive = True
            Exit Function
        End If
    Next objFile
    ' Recursively search through subfolders
    For Each objSubFolder In objFolder.SubFolders   '-----------edited
        'If InStr(1, objSubFolder.Path, "appda", vbTextCompare) > 0 Then Stop
        If FileExistsRecursive(objSubFolder.Path, fileName) Then  '------------edited
            Set FSO = Nothing
            FileExistsRecursive = True
            Exit Function
        End If
    Next objSubFolder         '-------------edited
    ' File not found
    Set FSO = Nothing
    FileExistsRecursive = False
End Function

Limitation: According to MS when using recursive function there is a limited size of variables used in the function. Since it calls the function a not predefined time this issue can occur when there are recursive calls in a higher amount. The outflow of it, is the reason of the malfunctioning of your code. When tested, I also didn’t get any error message, the code finished with Moved, but the files remained in their original positions. Probably this means that in a case like this the function returned a false positive result). When I limited the search area the modified code works w/o issue. Limit the search range as narrow as you can or apply some other workaround which reduce the recursive call. More info here from Microsoft.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật