I have a code that is working and is organizing files by extension. However, it works in only one folder at this time.
Suppose in a parent folder I have 500 subfolders and in each subfolder, there are files with different extensions (e.g. XML, PDF, Word, text, etc). Currently, I need to select each subfolder one at a time and move files into folders by extension via the below code.
However, I need a method where when I select a parent directory, the code should read each subfolder and in each subfolder create folders by extension and move the files to it.
Option Explicit
Sub OrganiseFilesbyFileType()
Dim fso As Scripting.FileSystemObject
Set fso = New Scripting.FileSystemObject
Dim Folderpath As String
Dim Fle As Scripting.File
Dim FoldpathPrompt As FileDialog
Set FoldpathPrompt = Application.FileDialog(msoFileDialogFolderPicker)
With FoldpathPrompt
.Title = "Select the folder you want to organise files in"
If .Show = -1 Then Folderpath = .SelectedItems(1)
End With
If Folderpath <> "" Then
Dim ParentPath As String
ParentPath = fso.GetParentFolderName(Folderpath)
Dim FolderName As String
FolderName = fso.GetFolder(Folderpath).Name
Dim NewFoldPath As String
NewFoldPath = ParentPath & "\" & FolderName & " - Organized" & "\"
Dim TheFolder As Scripting.Folder
Set TheFolder = fso.GetFolder(Folderpath)
fso.CreateFolder NewFoldPath
For Each Fle In TheFolder.Files
If Not fso.FolderExists(NewFoldPath & Fle.Type) Then
fso.CreateFolder (NewFoldPath & Fle.Type)
End If
Fle.Copy NewFoldPath & Fle.Type & "\" & Fle.Name
Next Fle
TheFolder.Delete
End If
End Sub
Organize Files By File Type
Main
Folder Picker
Subfolder Paths To Collection
Move Files To Type Folders