copying files from multiple subfolders using vba - excel

I've seen some documentation on this but so far, nothing that I've been able to replicate for my specific project.
My code points at a directory that contains 60 or so subfolders. Within these subfolders are multiple files .PDF/.XLS etc. The following code works fine if the files are not embedded in the subfolders but what I need to do is be able to loop through the subfolders and pull the files themselves to move. Also, is there a way to eventually pull files by wildcard name? Thanks in advance for any help.
Dim FSO As Object
Dim FromPath As String
Dim ToPath As String
Dim Fdate As Date
Dim FileInFromFolder As Object
FromPath = "H:\testfrom\"
ToPath = "H:\testto\"
Set FSO = CreateObject("scripting.filesystemobject")
For Each FileInFromFolder In FSO.getfolder(FromPath).Files
Fdate = Int(FileInFromFolder.DateLastModified)
If Fdate >= Date - 1 Then
FileInFromFolder.Copy ToPath
End If
Next FileInFromFolder
End Sub

You can also use recursion. Your folder can have subfolders having subfolders having ...
Public Sub PerformCopy()
CopyFiles "H:\testfrom\", "H:\testto\"
End Sub
Public Sub CopyFiles(ByVal strPath As String, ByVal strTarget As String)
Set FSO = CreateObject("scripting.filesystemobject")
'First loop through files
For Each FileInFromFolder In FSO.getfolder(strPath).Files
Fdate = Int(FileInFromFolder.DateLastModified)
If Fdate >= Date - 1 Then
FileInFromFolder.Copy strTarget
End If
Next FileInFromFolder
'Next loop throug folders
For Each FolderInFromFolder In FSO.getfolder(strPath).SubFolders
CopyFiles FolderInFromFolder.Path, strTarget
Next FolderInFromFolder
End Sub

I managed to get this code to work. It copies all folders / files and sub folders and their files to the new destination (strTarget).
I have not added checks and balances like 1) if the files and folders exist already. 2) if the source files are open etc. So those additions could be useful.
I got this code from Barry's post but needed to change it to make it work for me, so thought i'd share it again anyway.
Hope this is useful though. . .
strPath is the source path and strTarget is the destination path. both paths should end in '\'
Note: one needs to add "Microsoft Scripting Runtime" under "Tools / References" for FSO to work.
==================== call ================================
MkDir "DestinationPath"
CopyFiles "SourcePath" & "\", "DestinationPath" & "\"
==================== Copy sub ===========================
Public Sub CopyFiles(ByVal strPath As String, ByVal strTarget As String)
Dim FSO As Object
Dim FileInFromFolder As Object
Dim FolderInFromFolder As Object
Dim Fdate As Long
Dim intSubFolderStartPos As Long
Dim strFolderName As String
Set FSO = CreateObject("scripting.filesystemobject")
'First loop through files
For Each FileInFromFolder In FSO.GetFolder(strPath).Files
Fdate = Int(FileInFromFolder.DateLastModified)
'If Fdate >= Date - 1 Then
FileInFromFolder.Copy strTarget
'end if
Next
'Next loop throug folders
For Each FolderInFromFolder In FSO.GetFolder(strPath).SubFolders
'intSubFolderStartPos = InStr(1, FolderInFromFolder.Path, strPath)
'If intSubFolderStartPos = 1 Then
strFolderName = Right(FolderInFromFolder.Path, Len(FolderInFromFolder.Path) - Len(strPath))
MkDir strTarget & "\" & strFolderName
CopyFiles FolderInFromFolder.Path & "\", strTarget & "\" & strFolderName & "\"
Next 'Folder
End Sub

I found the solution here:
Private Sub Command3_Click()
Dim objFSO As Object 'FileSystemObject
Dim objFile As Object 'File
Dim objFolder As Object 'Folder
Const strFolder As String = "H:\testfrom2\"
Const strNewFolder As String = "H:\testto\"
Set objFSO = CreateObject("Scripting.FileSystemObject")
For Each objFolder In objFSO.GetFolder(strFolder & "\").SubFolders
'If Right(objFolder.Name, 2) = "tb" Then
For Each objFile In objFolder.Files
'If InStr(1, objFile.Type, "Excel", vbTextCompare) Then
On Error Resume Next
Kill strNewFolder & "\" & objFile.Name
Err.Clear: On Error GoTo 0
Name objFile.Path As strNewFolder & "\" & objFile.Name
'End If
Next objFile
'End If
Next objFolder
End Sub

Related

How to delete .xls files using VBA?

I am no expert when it comes to using VBA. However, I have a task to convert thousnds of files located in folders and sub folders. I have found online the below code and my question is: can the code be modified in a way that it can delete the old .xls files after conversion?
Public Sub test()
RenameFilesInFolders "M:\test\", True
MsgBox "Finished"
End Sub
Public Sub RenameFilesInFolders(path As String, Optional recurse As Boolean)
Dim fso As Object, fldr As Object
If Right(path, 1) <> "\" Then
path = path & "\"
End If
Set fso = CreateObject("Scripting.FileSystemObject")
Set fldr = fso.GetFolder(path)
renameFiles fldr, recurse
End Sub
Private Sub renameFiles(fldr As Object, recurse As Boolean)
Dim file As Object, subFldr As Object
For Each file In fldr.Files
changeFileExtension file
Next
If recurse And fldr.SubFolders.Count > 0 Then
For Each subFldr In fldr.SubFolders
renameFiles subFldr, recurse
Next
End If
End Sub
Private Sub changeFileExtension(file As Object)
Dim xlFile As Workbook
Dim strCurrentFileExt As String
Dim strNewFileExt As String
Dim strNewName As String
strCurrentFileExt = ".xls"
strNewFileExt = ".xlsx"
strNewName = file.Name
If Right(strNewName, Len(strCurrentFileExt)) = strCurrentFileExt Then
Set xlFile = Workbooks.Open(file.path, , True)
strNewName = Replace(strNewName, strCurrentFileExt, strNewFileExt)
Application.DisplayAlerts = False
Select Case strNewFileExt
Case ".xlsx"
xlFile.SaveAs file.ParentFolder & "\" & strNewName, XlFileFormat.xlOpenXMLWorkbook
Case ".xlsm"
xlFile.SaveAs file.ParentFolder & "\" & strNewName, XlFileFormat.xlOpenXMLWorkbookMacroEnabled
End Select
xlFile.Close
Application.DisplayAlerts = True
End If
End Sub
Store path (called in your RenameFilesInFolders Sub) in a variable (for example PathToFile) and use this command : Kill PathToFile.
Afterwards you can even check if the file is deleted with this (if you enabled Microsoft Scripting Runtime) :
Dim FSO As FileSystemObject
Set FSO = CreateObject("Scripting.FileSystemObject")
Dim PathToFile As String
If (FSO.FileExists(PathToFile) Then 'If the file still exists
'Your code
End If
Set FSO = Nothing

How to loop through subfolders?

The following code works for specified folder.
How to get it to work for all subfolders of X:\DataArchive\CMM\reports\?
Sub Copying()
Dim FSO As Object
Dim sFile As String
Dim sSFolder As String
Dim sDFolder As String
Dim fileExtn As String
fileExtn = ".PDF" ''File extension
sSFolder = "X:\DataArchive\CMM\reports\2019_01\" ''Source folder
sDFolder = "C:\Users\sc00709\Desktop\501 28\" ''Destination folder
Dim i As Integer
i = 2
Do While i < 74
With ThisWorkbook
''Filename
sFile = Dir(sSFolder & "364_040_501_0_D_OP270_INSP_" & _
Worksheets("50128").Cells(i, 2) & "*" & fileExtn)
''Create Object for File System
Set FSO = CreateObject("Scripting.FileSystemObject")
If Not FSO.FileExists(sSFolder & sFile) Then
ElseIf Not FSO.FileExists(sDFolder & sFile) Then
''Copying
FSO.CopyFile (sSFolder & sFile), sDFolder, TRUE
Else
End If
End With
i = i + 1
Loop
MsgBox "You did it!", vbInformation, "Done!"
End Sub
Here is code to loop through all the folders in a folder
Sub Main()
Dim FileSystem As Object
Set FileSystem = CreateObject("Scripting.FileSystemObject")
ExecuteOnAllSubFolders FileSystem.GetFolder("X:\DataArchive\CMM\reports\")
End Sub
Sub ExecuteOnAllSubFolders(Folder)
Dim SubFolder
For Each SubFolder In Folder.SubFolders
ExecuteOnAllSubFolders SubFolder
'Perform your operations here
Next
'Perform your operations and here
End Sub

Search for a file in folders and sub folders using file name if found copy to another folder in vba macros

Search for a file in folders and sub folders using file name if found copy to another folder in vba macros
The code shows no error but the file is not copying from the folder, i need to loop through sub folders and find a file.
Sub copy_files_from_subfolders()
Dim fso As Object
Dim fld As Object
Dim fsofile As Object
Dim fsofol As Object
sourcepath = "FINAL CUT\"
destinationpath = "Desa\MECA\"
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 Right(fsofile, 6) = 566978 Then
fsofile.Copy destinationpath
End If
Next
Next
End If
End Sub
You're searching for the number using the Right-function, but this fails to take into account the file-extension that follows it. You could try something like (assuming the extension is the same):
Right(fsofile, 10) = "566978.txt" ''change extension to whatever
If the file-extensions aren't of the same length, you could determine the position of the dot in the name and use the Mid-function.
Alternatively, you could just check if the numbers you're looking for occur within the filename using, instead of the Right-function:
If InStr(1, fsofile, "566978") <> 0 then
This should only cause issues if there are files with longer strings of numbers, because for example you could have a file named "123556978123.pdf", which would be a false positive.
Here is the answer i found
Sub copy_files_from_subfolders()
Dim fso As Object
Dim fld As Object
Dim fsofile As Object
Dim fsofol As Object
sourcepath = "FINAL CUT\"
destinationpath = "Desa\MECA\"
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, 566978 & "_PTA") = 1 Then
fsofile.Copy destinationpath
End If
Next
Next
End If
End Sub

VBA - Copy multiple selected files from 1 folder to another

I am looking for a way to select multiple .jpg file in a folder and copy it to another folder. This is the code I am working with, but it doesn't seem to be able to move it to the destination file.
I'm also using an excel worksheet where I paste those filenames which I want to copy in Row A.
Sub CopyFiles()
Dim xDir As String
Dim xFile As String
Dim xRow As Long
Dim FSO As Object
Dim FromPath As String
Dim ToPath As String
Dim FileExt As String
Dim FNames As String
FromPath = "Directory" 'Folder From
ToPath = "Directory" 'Folder To
Worksheets("Files to Copy").Activate
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
If .Show = -1 Then
xDir = .SelectedItems(1)
xFile = Dir(xDir & Application.PathSeparator & "*")
Do Until xFile = ""
xRow = 0
On Error Resume Next
xRow = Application.Match(xFile, Range("A:A"), 0)
If xRow > 0 Then
Name xDir & Application.PathSeparator & xFile As _
ToPath & Cells(xRow, "B").Value
End If
xFile = Dir
Loop
End If
End With
End Sub
Maybe something like this...copy or Move one file
For one file you can use the VBA Name and FileCopy function and for entire folders or a lot of files use the other macro example's on this page.
Copy or Move one file
For one file you can use the VBA Name and FileCopy function and for entire folders or a lot of files use the other macro example's on this page.
Sub Copy_One_File()
FileCopy "C:\Users\Ron\SourceFolder\Test.xls", "C:\Users\Ron\DestFolder\Test.xls"
End Sub
OR
Sub Move_Rename_One_File()
'You can change the path and file name
Name "C:\Users\Ron\SourceFolder\Test.xls" As "C:\Users\Ron\DestFolder\TestNew.xls"
End Sub
Sub CopyFiles()
'// Tools -> References -> Microsoft Scripting Runtime
Dim xRow As Long
Dim FSO As FileSystemObject
Dim FromPath$, ToPath$
Dim xFile As File
Dim xFolder As Folder
FromPath = "Directory" 'Folder From
ToPath = "Directory" 'Folder To
Worksheets("Files to Copy").Activate
Set fso = New FileSystemObject
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
If Not .Show Then Exit Sub
Set xFolder = FSO.GetFolder(.SelectedItems(1))
For Each xFile In xFolder.Files
On Error Resume Next
xRow = Application.Match(xFile.Name, Range("A:A"), 0)
If Err = 0 Then
xFile.Copy ToPath & Cells(xRow, "B").Value
End If
On Error GoTo 0
Next
End With
End Sub

move files from one folder to another

actually I am searching for code to move excel files from one folder to another if there is any way to do so Please someone help me. I am very sorry but I dont know how to do coding as I have never used VBA in fact I see it for the first time.
I will be grateful to you
Sub MoveFiles()
Dim FSO As Object
Dim SourceFileName As String, DestinFileName As String
Set FSO = CreateObject("Scripting.Filesystemobject")
SourceFileName = "C:\Users\Jun.xlsx"
DestinFileName = "C:\Users\Desktop\Jun.xlsx"
FSO.MoveFile Source:=SourceFileName, Destination:=DestinFileName
MsgBox (SourceFileName + " Moved to " + DestinFileName)
End Sub
Try with the below code
Sub test()
Set fso = CreateObject("scripting.filesystemobject")
fso.MoveFile Source:="C:\work\test1.xlsx", Destination:="c:\work\movecheck\" ' replace with source and destination as required.
End Sub
Below is code which moves only Excel (xlsx) files from source folder into destination folder. Other types files will be left in the destination folder.
Sub MoveFiles()
Dim sourceFolderPath As String, destinationFolderPath As String
Dim FSO As Object, sourceFolder As Object, file As Object
Dim fileName As String, sourceFilePath As String, destinationFilePath As String
Application.ScreenUpdating = False
sourceFolderPath = "D:\SourceFolder"
destinationFolderPath = "D:\DestinationFolder"
Set FSO = CreateObject("Scripting.FileSystemObject")
Set sourceFolder = FSO.Getfolder(sourceFolderPath)
For Each file In sourceFolder.Files
fileName = file.Name
If InStr(fileName, ".xlsx") Then ' Only xlsx files will be moved
sourceFilePath = file.Path
destinationFilePath = destinationFolderPath & "\" & fileName
FSO.MoveFile Source:=sourceFilePath, Destination:=destinationFilePath
End If ' If InStr(sourceFileName, ".xlsx") Then' Only xlsx files will be moved
Next
'Don't need set file to nothing because it is initialized in for each loop
'and after this loop is automatically set to Nothing
Set sourceFolder = Nothing
Set FSO = Nothing
End Sub
If you need move only one file the best solution is:
Name sourceFolderPath & fileName As destinationFilePath
You can use the Filesystemobject:
Dim FSO as Object
Set FSO = CreateObject("Scripting.Filesystemobject")
FSO.MoveFile("SourceFileName", "TargetFileName")
Feel free to comment, if you need further instructions.
Sub move_data()
'Move test data to folder
Dim FSO As Object
Dim FromPath As String
Dim ToPath As String
Dim Fdate As Date
Dim FileInFromFolder As Object
MkDir "D:\TEST\" 'Create new folder name TEST in D:
FromPath = "E:\test\" 'Source files
ToPath = "D:\TEST\" 'Target destination
Set FSO = CreateObject("scripting.filesystemobject")
If FSO.FolderExists(FromPath) = False Then
MsgBox FromPath & " doesn't exist"
Exit Sub
End If
For Each FileInFromFolder In FSO.getfolder(FromPath).Files
FileInFromFolder.move ToPath
Next FileInFromFolder
End Sub
try :
Sub movefile()
Dim fso As New FileSystemObject
Dim fil As file
Dim SourcePath, BackUpPath As String
SourcePath = "C:\mydata\"
BackUpPath = "G:\Backup\"
For Each fil In fso.GetFolder(SourcePath).Files
fName = fso.GetFileName(fil)
Name fil As BackUpPath & fName
Next fil
End Sub

Resources