Macro to delete backup files in folder and sub-folder

howard

Well-known Member
Joined
Jun 26, 2006
Messages
6,561
Office Version
  1. 2021
Platform
  1. Windows
I would like to to delete all back files eg Backup TB in folder TB as well as sub-folders
 
Thanks for the reply. When running the macro the backup files (xlk) files in the folder C:\test and its sub-folders is not deleted
 
Upvote 0

Excel Facts

Can you sort left to right?
To sort left-to-right, use the Sort dialog box. Click Options. Choose "Sort left to right"
Since those names are starting with "backup", the wildcard * needs to be on the other side. If you want to delete files with the name "backup" and it could have other text or numbers on either side, just use the wildcard on both sides (*backup*.*).

Just run the macro called "run" on sample files and subfolders from a module. Just change the wildcard * for your needs.
Code:
Option Explicit
Option Compare Text

Sub DeleteBackupFiles(ByVal FolderPath As String)
    ' Author:  Leith Ross
    Dim File As Object
    Dim Folder As Object
    Dim FSO As Object
    Dim SubFolder As Object
    
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set Folder = FSO.GetFolder(FolderPath)
            
    For Each File In Folder.Files
        If File.Name Like "[COLOR=#ff0000]*backup*[/COLOR].*" Then
           File.Delete
        End If
    Next File
                
    For Each SubFolder In Folder.SubFolders
        DeleteBackupFiles SubFolder
    Next SubFolder
                
End Sub

Sub Run()
    DeleteBackupFiles "C:\test"
End Sub
 
Upvote 0
Thanks for the help, code works perfectly
 
Upvote 0

Forum statistics

Threads
1,214,975
Messages
6,122,538
Members
449,088
Latest member
RandomExceller01

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