0

I am trying to come up with a routine that copies only certain files out of a directory, and all sub-directories, and pastes each copied file into a destination directory. I came up with the code below, which copies all files, in a filtered list, into a destination folder, but I can't figure out how to do a recursive loop through the hierarchy. Any guidance on this would be greatly appreciated.

Sub CopyFilteredFiles()

Dim rng As Range, cell As Range
Dim sht As Worksheet
Dim LastRow As Long
Dim FSO As Object
Dim FromPath As String
Dim ToPath As String
Dim lastChar As Integer
Dim fileName As String

DestinationFolder = "C:\Users\ryans\OneDrive\Desktop\AllYAML\"
Set sht = ActiveSheet
LastRow = sht.Cells(sht.Rows.Count, "D").End(xlUp).Row

Set rng = Range("D14:D" & LastRow)
Set FSO = CreateObject("scripting.filesystemobject")

    For Each cell In rng.SpecialCells(xlCellTypeVisible)
        If cell.Value <> "" Then
        CopyFile = cell.Value
        Debug.Print cell.Value
            lastChar = InStrRev(CopyFile, "\")
            fileName = Mid(CopyFile, lastChar + 1, 199)
            On Error Resume Next

            FSO.CopyFile Source:=CopyFile, Destination:=DestinationFolder & fileName

        End If
    Next cell

End Sub
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
ASH
  • 20,759
  • 19
  • 87
  • 200

0 Answers0