0

I need to copy files from folders and subfolders, but the below code search for only subfolders inside the main folder. But there are also some subfolders inside the subfolders Eg : C:\abc\bca - for this abc is main folder and bca is subfolder, the code is working for this. For c:\abc\bca\cab or c:\abc\zxc\cvg it is not working in folders in subfolders, Please assist me. Thanks in Advance

Sub copy_files_from_subfolders()

Dim fso As Object
Dim fld As Object
Dim fsofile As Object
Dim fsofol As Object
Dim filename As String
Dim snumber As Double
snumber = InputBox("Enter the Number", "Message from D")
filename = "_PTA.pdf"
sourcepath = "\\chec.local\"
destinationpath = "R:\Desa"

If Right(sourcepath, 1) <> "\" Then
sourcepath = sourcepath & "\"
End If

Set fso = CreateObject("scripting.filesystemobject")
Set fld = fso.GetFolder(sourcepath)
If fso.FolderExists(fld) Then
    For Each fsofol In fso.GetFolder(sourcepath).SubFolders
        For Each fsofile In fsofol.Files
            If InStr(1, fsofile.Name, snumber) = 1 Then
            MsgBox "Documents Copied"
            fsofile.Copy destinationpath
            End If
        Next
    Next
End If
End Sub
Pᴇʜ
  • 56,719
  • 10
  • 49
  • 73
DESA
  • 1
  • 2
  • 2
    You need to redesign the sub so that it can call itself with a subfolder as the new root. The newly called sub may find more subfolders so then it calls itself again. –  Feb 21 '19 at 14:11
  • as am new to vba am not able to understand your comments can you please expan it thanks – DESA Feb 21 '19 at 14:14
  • 1
    The concept @user11087823 is referring to is called "recursion". Here is a [solution that uses recursion](https://stackoverflow.com/a/26149102/4717755) to copy files within folders/subfolders. You can adapt the example to suit your own needs. – PeterT Feb 21 '19 at 14:36
  • I referred the example but still am unclear, is there any other solution. thanks in advance – DESA Feb 21 '19 at 16:24
  • 1
    Yes there are other solutions. But if you are new to VBA, they would likely be more difficult for you to implement. – Ron Rosenfeld Feb 21 '19 at 21:07
  • @Ron Rosenfeld Can you please help me to break this – DESA Feb 22 '19 at 12:27
  • 1
    What help do you need? There are plenty of examples of searching through subfolders on SO. Do a search and adapt what you find to your specific problem. An example of a somewhat different solution, using the `Shell` can be found at my answer to [Search through subfolders back to root directory](https://stackoverflow.com/questions/53713804/recursive-search-through-subfolders-back-to-root-directory) – Ron Rosenfeld Feb 22 '19 at 13:23

0 Answers0