Hi
I need to create a folder (e.g. "ABCD_12.3") and then copy all the files starting with "ABCD_12_3*.*" to this folder. The folder is off "C:\Spreadsheet\".
Any idea how to do this in VBA please?
Thanks.
Robie
Copy Files to folder
-
- gamma jay
- Posts: 25455
- Joined: 17 Mar 2010, 17:33
- Location: Cape Town
Re: Copy Files to folder
Do you need the code to create the folder or will one already exist that the code can simply copy the files to?
Regards,
Rudi
If your absence does not affect them, your presence didn't matter.
Rudi
If your absence does not affect them, your presence didn't matter.
-
- 5StarLounger
- Posts: 656
- Joined: 18 Feb 2010, 14:26
Re: Copy Files to folder
Thanks for quick response Rudi.Rudi wrote:Do you need the code to create the folder or will one already exist that the code can simply copy the files to?
The folder has to created but it may exist already.
-
- gamma jay
- Posts: 25455
- Joined: 17 Mar 2010, 17:33
- Location: Cape Town
Re: Copy Files to folder
Try this.
Place in a standard Excel VBA module.
Place in a standard Excel VBA module.
Code: Select all
Sub CopyToFolder()
Dim FSO As Object
Dim dFolder As String
Dim sFolder As String
Dim sFile As String
sFolder = "C:\Spreadsheet\" 'Specify Your Source Folder
dFolder = "C:\ABCD_12.3\" 'Specify Destination Folder
Set FSO = CreateObject("Scripting.FileSystemObject")
If Not FSO.FolderExists(dFolder) Then FSO.CreateFolder (dFolder)
If Not FSO.FolderExists(sFolder) Then
MsgBox "Source Folder Not Found", vbInformation, "Source Not Found!"
Exit Sub
Else
sFile = Dir(sFolder)
Do While Len(sFile) > 0
If Left(sFile, 9) = "ABCD_12_3" Then
FSO.CopyFile (sFolder & sFile), dFolder
End If
sFile = Dir
Loop
MsgBox "Successfully Copied All Files to Destination.", vbInformation, "Done!"
End If
End Sub
Regards,
Rudi
If your absence does not affect them, your presence didn't matter.
Rudi
If your absence does not affect them, your presence didn't matter.
-
- 5StarLounger
- Posts: 656
- Joined: 18 Feb 2010, 14:26
Re: Copy Files to folder
Thank you so much Rudi.Rudi wrote:Try this.
Place in a standard Excel VBA module.
Code: Select all
Sub CopyToFolder() Dim FSO As Object Dim dFolder As String Dim sFolder As String Dim sFile As String sFolder = "C:\Spreadsheet\" 'Specify Your Source Folder dFolder = "C:\ABCD_12.3\" 'Specify Destination Folder Set FSO = CreateObject("Scripting.FileSystemObject") If Not FSO.FolderExists(dFolder) Then FSO.CreateFolder (dFolder) If Not FSO.FolderExists(sFolder) Then MsgBox "Source Folder Not Found", vbInformation, "Source Not Found!" Exit Sub Else sFile = Dir(sFolder) Do While Len(sFile) > 0 If Left(sFile, 9) = "ABCD_12_3" Then FSO.CopyFile (sFolder & sFile), dFolder End If sFile = Dir Loop MsgBox "Successfully Copied All Files to Destination.", vbInformation, "Done!" End If End Sub
That works beautifully.