Delete files of a specific type in subfolders

hendersam

New Member
Joined
May 9, 2011
Messages
1
I have this vba code that deletes files of a specific type ("File") from the path indicated by the range name ("TMPath"):

Sub JunkFiles()
fPath = [TMPath]

Set fso = CreateObject _
("Scripting.FileSystemObject")

Set folder = fso.GetFolder(fPath)

For Each file In folder.Files

If fso.GetFile(file).Type = "File" Then
file.Delete
End If

Next

Set folder = Nothing
Set fso = Nothing
End Sub

I want to delete these files from all subfolders within the specified folder (fPath). How can this code be modified to loop through all subfolders of this folder?

Thanks,

Sam
 

Excel Facts

How to create a cell-sized chart?
Tiny charts, called Sparklines, were added to Excel 2010. Look for Sparklines on the Insert tab.
Not well tested, but I think:
Rich (BB code):
Option Explicit
    
Sub exa6()
Dim fso     As Object '<--- FileSystemObject
Dim fsoFol  As Object '<--- Folder
    
    Set fso = CreateObject("Scripting.FileSystemObject")
    ' Change ThisWorkbook.Path to suit
    Set fsoFol = fso.GetFolder(ThisWorkbook.Path)
    
    Call DelFiles(fso, fsoFol)
End Sub
    
Function DelFiles(oFSO As Object, Fol As Object)
'Dim Fil As File, oFol As Folder
Dim Fil As Object, oFol As Object
    For Each Fil In Fol.Files
        If Fil.Type = "Microsoft Word Document" Then
            Fil.Delete
        End If
    Next
    
    For Each oFol In Fol.SubFolders
        Call DelFiles(oFSO, oFol)
    Next
End Function
 
Last edited:
Upvote 0

Forum statistics

Threads
1,224,590
Messages
6,179,756
Members
452,940
Latest member
rootytrip

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top