1

I am creating an archiving system where I need to sort files into folders.
I create the folders automatically by mentioning the names of folder in an Excel sheet.

Now I need to copy the files with similar names in that respective folder.
E.g. A folder is created with the name "Ashley Davidson". All the files which are in one source folder and whose file name starts with Ashley Davidson should be copied to this folder.

There will be more than 500 folders and more than 10,000 files to be copied in these folders every week.

The code below creates the folders.
How can I copy the files based on similar name to these folders?

Important
The names of folders will be constant.
The start of the names of files will be similar but users add other words like date, age, sheet 1, sheet 2 etc., therefore List of Partial name concept will probably work here.

Examples of folder names
Folder Names

Example of file names
File Names

Code to create folders:

Sub MakeFolders()

    Dim sh As Worksheet, lastR As Long, arr, i As Long, rootPath As String
    
    Set sh = ActiveSheet
    lastR = sh.Range("A" & sh.Rows.Count).End(xlUp).Row
    arr = sh.Range("A2:A" & lastR).Value2
    rootPath = ThisWorkbook.Path & "\"

    For i = 1 To UBound(arr)
        If arr(i, 1) <> "" And noIllegalChars(CStr(arr(i, 1))) Then
            If Dir(rootPath & arr(i, 1), vbDirectory) = "" Then
                MkDir rootPath & arr(i, 1)
            End If
        Else
            MsgBox "Illegals characters or empty cell (" & sh.Range("A" & i + 1).Address & ")..."
        End If
    Next i

End Sub

Function noIllegalChars(x As String) As Boolean
   Const illCh As String = "*[\/\\"":\*?]*"
   If Not x Like illCh Then noIllegalChars = True
End Function
Community
  • 1
  • 1
Salman Shafi
  • 249
  • 9
  • The folder names and file names will never deviate from their base form, right? Never go from "Rober Barton" to "Robert Barton Oct 17 2022" or "Rober Bart Sheet 2" Because if so, you can use two for each loops, one to iterate through the files and one to iterate through the folder names (in case that file remains existing) with `If inStr(folderName,fileName) >0 Then....` https://stackoverflow.com/a/39890893/19353309 – Notus_Panda Nov 25 '22 at 12:46
  • The Folder names will be constant and remain same every time, however the initial part of the file names will be same but as mentioned users do add some other words in file names as well. It will be okay if i need to run 2 separate codes. – Salman Shafi Nov 25 '22 at 12:50
  • Dear @FaneDuru this is the new question – Salman Shafi Nov 25 '22 at 13:16
  • 1
    OK, but you need to supply some pieces of information... Do you want mixing the above code with appropriate files name, **for the respective newly created folder**? Did you already created the necessary folders using the above code and now you want iterating between the partial file name to match the appropriate folder? Where should be the files in discussion located (their folder path)? What type are the files in discussion? Excel workbooks or of a different type? And finally you can state that all these files name starts with such a folder name. Would this understanding be a correct one? – FaneDuru Nov 25 '22 at 13:17
  • Dear @FaneDuru yes you have have understood the question correctly. Both ways are fine, if it is possible to amend the above-mentioned code that would be wonderful, otherwise providing separate code (1 for folder creation which I already have and 1 for files movement) is also fine. In the first step i will create the folders and then will start copying/moving the files in them using second code. The files and Excel sheet will be saved in the same folder (i.e. E:\Archive ) – Salman Shafi Nov 25 '22 at 13:30
  • and the destination where the folders needs to be created and after that files needs to be moved will be in separate folder (i.e. E:\Archive\2022) the files are in different format includes .XML .PDF . RAR .ZIP and yes all these files names starts with a folder name – Salman Shafi Nov 25 '22 at 13:30
  • So, the files in discussion must be taken from a folder having the name **exactly** as the ones shown in your picture? Or all of them are somewhere in a folder (like I initially understood) and be taken from there? Now I need to finish something urgent and I will look to your comment after about an hour... – FaneDuru Nov 25 '22 at 13:38
  • Dear @FaneDuru the names mentioned in above picture is just example and to understand the criteria and pattern of files and folders, there will be more than 500 folders which needs to be created and more than 10,000 files which needs to be moved in these folders however the initial file names will start with same as the names of Folders. since i need to sort all these files folder wise, therefore i will copy and paste all the files into one folder (i.e. E:\Archive) so that it will be easy. – Salman Shafi Nov 25 '22 at 13:42
  • I am also leaving for next 4 to 6 hours and will see if any details were required from my side. Thank you so much – Salman Shafi Nov 25 '22 at 14:04
  • Understanding the context may be important, but not clear the next issues: Where from the files to be taken and based on what? Where to be copied/moved? To be taken from the folder exactly named as string (example) in A:A column? Or from a common folder for all? To be placed in the folder exactly named as the string in A:A, or in a common folder? Should they be **copied or moved**? You did not answer my question: **"Where should be the files in discussion located (their folder path)?"**. I mean where from to be taken. What is the role of the already created folders? – FaneDuru Nov 25 '22 at 14:52

2 Answers2

0

My code works from having the new Folders in the same folder as the workbook you've created said folders from (as it is in your code) and the files to be copied were in a seperate folder in the same path as your workbook; I found that easier to work with since then the only files in that folder are files to be copied, not extra folders within.

Sub copyFilesToFolder()
    Dim lRow As Long
    Dim wb As Workbook
    Dim ws As Worksheet
    Dim ccell As Range
    Dim fsO As Object, oFolder As Object, oFile As Object
    Dim pathFiles As String, sFolderPath As String, sSource As String, sDestination As String
    
    Set wb = ActiveWorkbook
    Set ws = wb.ActiveWorksheet
    lRow = Range("A" & Rows.Count).End(xlUp).Row
    pathFiles = "Q:\WHERE YOUR ORIGINAL WORKBOOK IS\Test\" 'could be gotten from wb technically
    
    Set fsO = CreateObject("Scripting.FileSystemObject")
    Set oFolder = fsO.GetFolder(pathFiles)
    For Each oFile In oFolder.Files 'go through all the files
        For Each ccell In Range("A2:A" & lRow).Cells 'go through all the folder-names
            'Debug.Print ccell.Value2
            'Debug.Print oFile.Name
            If InStr(oFile.Name, ccell.Value2) > 0 Then 'if folder name is in file name
                sFolderPath = wb.Path & "\" & ccell.Value2 & "\"
                If Dir(sFolderPath, vbDirectory) <> "" Then 'if Folder exists
                    sDestination = sFolderPath & oFile.Name
                    If Dir(sDestination) = "" Then 'file doesn't exist yet
                        sSource = pathFiles & oFile.Name
                        'Debug.Print sSource
                        'Debug.Print sDestination
                        Call fsO.CopyFile(pathFiles & oFile.Name, sFolderPath & oFile.Name)
                        GoTo Skip
                    End If
                Else
                    MsgBox ("Folder " & ccell.Value2 & " doesn't exist yet")
                End If
            End If
        Next ccell
Skip:
    Next oFile
    
End Sub

Hope this helps :)

Notus_Panda
  • 1,402
  • 1
  • 3
  • 12
0

You did not answer the clarification question and I need to leave my office. The next code assumes that all files exist in a common folder and they should be moved in the folder exactly named as the string in column A:A of the active sheet. It is able to move or copy the file, according to the line you should uncomment:

Sub moveMatchedFilesInAppropriateFolders()
    Dim sh As Worksheet, lastR As Long, filesPath As String, fileName As String, foldersRoot As String, folderPath As String
    Dim arr, boolNotFound As Boolean, i As Long
    
    Set sh = ActiveSheet
    lastR = sh.Range("A" & sh.rows.count).End(xlUp).row
    
    arr = sh.Range("A2:A" & lastR).Value2
    foldersRoot = ThisWorkbook.Path & "\" 'use here the root folder for folders
    filesPath = "your files to be processed folder"   'use here the path where the files can be found
    Set fso = CreateObject("Scripting.FileSystemObject") 'to check if file exists

    For i = 1 To UBound(arr)
        boolNotFound = False
        If Dir(foldersRoot & arr(i, 1), vbDirectory) <> "" Then
            folderPath = foldersRoot & arr(i, 1) & "\"
        Else
            MsgBox arr(i, 1) & " folder could not be found!" & vbCrLf & _
                           "Please, note and correct it after copying the matching ones and run the code again!"
            boolNotFound = True
        End If
        If Not boolNotFound Then
                fileName = Dir(filesPath & arr(i, 1) & "*.*")
                
                Do While fileName <> ""
                If Not fso.FileExists(folderPath & fileName) Then 'move/copy only if it does not exist in destination fld
                    'uncomment the way you need (moving or copying):
                    'Name filesPath & fileName As folderPath & fileName    'the file is moved
                    'FileCopy filesPath & fileName, folderPath & fileName   'the file is copied
                End If
                fileName = Dir
            Loop
         End If
    Next i
End Sub

Not tested, but it should work.

If you need something else, please better answer my last clarifications question.

Besides all that, I think it would be good to place a marker in B:B column, for not found folders, if any. In this way, the code can be adapted that at the next run to only run the ones having the marker (and delete it, if the string has been corrected and the folder has been found).

FaneDuru
  • 38,298
  • 4
  • 19
  • 27
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/249931/discussion-on-answer-by-faneduru-to-copy-files-with-similar-name-into-folders). – sideshowbarker Nov 27 '22 at 21:37