huskersippi
New Member
- Joined
- Feb 10, 2017
- Messages
- 7
I am able to copy all files from one subfolder but need to loop through directory and copy files from all subfolders with the same name.
Currently my folder structure is as such: C:\Users\Me\Desktop\TestLoop\Test-277\O&M\CopyFinal
So in this instance I would copy all .doc files from the CopyFinal subfolder. The issue is different names among the folder tree. The folder "Test-277" would be the name to change in the directory.
For example:
C:\Users\Me\Desktop\TestLoop\Test-277\O&M\CopyFinal
C:\Users\Me\Desktop\TestLoop\Test-278\O&M\CopyFinal
C:\Users\Me\Desktop\TestLoop\Test-279\O&M\CopyFinal
How can I use a wildcard value "Test-*" to allow my script to loop through entire directory and if there is a folder named CopyFinal, copy all files?
Here is my attempt so far:
Currently my folder structure is as such: C:\Users\Me\Desktop\TestLoop\Test-277\O&M\CopyFinal
So in this instance I would copy all .doc files from the CopyFinal subfolder. The issue is different names among the folder tree. The folder "Test-277" would be the name to change in the directory.
For example:
C:\Users\Me\Desktop\TestLoop\Test-277\O&M\CopyFinal
C:\Users\Me\Desktop\TestLoop\Test-278\O&M\CopyFinal
C:\Users\Me\Desktop\TestLoop\Test-279\O&M\CopyFinal
How can I use a wildcard value "Test-*" to allow my script to loop through entire directory and if there is a folder named CopyFinal, copy all files?
Here is my attempt so far:
Code:
Sub Copy_Folder()'This example copy all files and subfolders from FromPath to ToPath.
'Note: If ToPath already exist it will overwrite existing files in this folder
'if ToPath not exist it will be made for you.
Dim FSO As Object
Dim FromPath As String
Dim ToPath As String
FromPath = "C:\Users\Me\Desktop\TestLoop\Test-277\O&M\CopyFinal" '<< Change
ToPath = "C:\Users\Me\Desktop\Destination" '<< Change
'If you want to create a backup of your folder every time you run this macro
'you can create a unique folder with a Date/Time stamp.
'ToPath = "C:\Users\Me\Desktop\Destination" & Format(Now, "yyyy-mm-dd h-mm-ss")
If Right(FromPath, 1) = "\" Then
FromPath = Left(FromPath, Len(FromPath) - 1)
End If
If Right(ToPath, 1) = "\" Then
ToPath = Left(ToPath, Len(ToPath) - 1)
End If
Set FSO = CreateObject("scripting.filesystemobject")
If FSO.FolderExists(FromPath) = False Then
MsgBox FromPath & " doesn't exist"
Exit Sub
End If
FSO.CopyFolder Source:=FromPath, Destination:=ToPath
MsgBox "You can find the files and subfolders from " & FromPath & " in " & ToPath
End Sub