Ранее, если вам нужно было собрать все папки, а затем скопировать папку, соответствующую условиям, будут собраны только папки, соответствующие условиям, и затем скопированы. Это более эффективно.
Option Explicit
Dim vR()
Dim n As Long
Dim str As String
Sub copyFileFromFolder()
Dim strFolder As String, TargetFolder As String
Dim i As Long
Dim vSplit
Dim Path As String
Dim Wb As Workbook
Dim FS As Scripting.FileSystemObject
Set FS = New Scripting.FileSystemObject
strFolder = "C:\Users\USER\Desktop\retrieve test\New folder\"
TargetFolder = "C:\Users\USER\Desktop\retrieve test\Lay\Lay\"
'*** The folder address below is for my test.
'strFolder = "C:\Users\Admin\Documents\" '<~~ for my test -->It corresponds to your New folder
'TargetFolder = "C:\Users\Admin\Documents\target\" '<~~ for my test
Set Wb = ThisWorkbook
str = Wb.Sheets("Sheet3").Range("B1")
SearchFolder strFolder
On Error Resume Next
For i = 1 To n
Path = vR(i)
Path = Replace(Path, strFolder, "")
vSplit = Split(Path, "\")
FS.CopyFolder vR(i), TargetFolder & vSplit(2)
Next i
'** Show Root folder's subfolders
With Sheets.Add ' set Sheets("your sheets's name)
.UsedRange.Offset(1).ClearContents
.Range("a2").Resize(n) = WorksheetFunction.Transpose(vR)
End With
Erase vR
n = 0
End Sub
Sub SearchFolder(strRoot As String)
Dim FS As Scripting.FileSystemObject
Dim fsFD As Folder
Dim f As Folder
Dim p As String
Dim s As String
Dim vSplit
On Error Resume Next
p = Application.PathSeparator
If Right(strRoot, 1) = p Then
Else
strRoot = strRoot & p
End If
Set FS = New Scripting.FileSystemObject
Set fsFD = FS.GetFolder(strRoot)
For Each f In fsFD.SubFolders
s = f.Path
s = Replace(s, "C:\Users\USER\Desktop\retrieve test\New folder\", "")
's = Replace(s, "C:\Users\Admin\Documents\", "")
vSplit = Split(s, "\")
If UBound(vSplit) = 2 Then
If InStr(vSplit(2), str) Then
n = n + 1
ReDim Preserve vR(1 To n)
vR(n) = f.Path
End If
End If
SearchSubfolder f
Next f
Set fsFD = Nothing
Set FS = Nothing
End Sub
Sub SearchSubfolder(objFolder As Folder)
Dim sbFolder As Object
Dim f As Folder
Dim s As String
Dim vSplit
Dim Wb As Workbook
Dim str As String
Set Wb = ThisWorkbook
str = Wb.Sheets("Sheet3").Range("B1")
For Each sbFolder In objFolder.SubFolders
s = sbFolder.Path
s = Replace(s, "C:\Users\USER\Desktop\retrieve test\New folder\", "")
's = Replace(s, "C:\Users\Admin\Documents\", "")
vSplit = Split(s, "\")
If UBound(vSplit) > 2 Then Exit Sub
SearchSubfolder sbFolder
If UBound(vSplit) = 2 Then
If InStr(vSplit(2), str) Then
n = n + 1
ReDim Preserve vR(1 To n)
vR(n) = sbFolder.Path
End If
End If
Next sbFolder
End Sub