Delete Selective Files

DanielS

Board Regular
Joined
Sep 4, 2011
Messages
53
I have a folder named C:\General\ which contains several subfolders. Each subfolder contains around 20 files with different extensions such as csv, txt, xls, zip etc. I wish to keep Ad*.*, Bv*.*, and La*.* and delete all other files in the subfolders. I am aware that files deleted cannot be restored again. i use Excel 2003. Please help me with a code to this.
 

Excel Facts

Will the fill handle fill 1, 2, 3?
Yes! Type 1 in a cell. Hold down Ctrl while you drag the fill handle.
Here's one way (No FSO reference needed)

Code:
Sub DelFiles()
    
    Dim AFile, RootPath As String
    Dim Counter As Integer
    Dim FilePaths()
    
    '[COLOR="Green"]Change these paths to your paths[/COLOR]
    FilePaths = Array("C:\General\001\", "C:\General\002\", "C:\General\003\")
    For Counter = 0 To UBound(FilePaths)

        RootPath = FilePaths(Counter)
        AFile = Dir(RootPath & "*.*")
        Debug.Print: Debug.Print Now
        Do
            Select Case UCase(Left(AFile, 2))
            Case Is = "AD", "BV", "LA"
                Debug.Print "Leaving " & RootPath & AFile
            Case Else
                Debug.Print "Deleting " & RootPath & AFile
                Kill RootPath & AFile
            End Select
            AFile = Dir()
        Loop While AFile <> ""
    Next Counter
End Sub
 
Upvote 0
Thanks for the code. Unfortunately, all files in the subfolder are getting deleted. Please note I wish to keep Ad*.*, Bv*.*, and La*.* (First letter uppercase, if that is important). Second problem is I have almost 22 to 25 subfolders every month in the General Folder. Putting all those subfolder names will make the code line very very lengthy. Any shortcut that it should automatically select each subfolder one by one?
 
Upvote 0
Thanks for the code. Unfortunately, all files in the subfolder are getting deleted.
I disagree with that test result; unless, of course, none of the files begin with these two letter codes; are there any leading spaces/characters perhaps?
This was tested before posting and desired results were achieved.
Please note I wish to keep Ad*.*, Bv*.*, and La*.* (First letter uppercase, if that is important).
Duly noted.
Second problem is I have almost 22 to 25 subfolders every month in the General Folder. Putting all those subfolder names will make the code line very very lengthy. Any shortcut that it should automatically select each subfolder one by one?

The version below will collect the sub-directories returned by Dir (excluding "." & "..")
Note: Added TestMode flag; see comments
Also added comments

Code:
Option Base 0
Sub DelFiles()
    Const TestMode = True    'True suppresses file-deletion; False processes file-deletion
    Dim AFile, RootPath, RetVal As String
    Dim i As Integer
    Dim DirPath()
    'Initialize
    RootPath = "C:\General\"
    ReDim DirPath(0)
    'Any shortcut that it should automatically select each subfolder one by one?
    'Collect Sub-Directories
    ChDir RootPath
    RetVal = Dir("*", vbDirectory)  'process ".", not needed
    RetVal = Dir()                  'process "..", not needed
    RetVal = Dir()                  'Get First to keep
    Do While RetVal <> ""
        If RetVal <> "" Then
            ReDim Preserve DirPath(UBound(DirPath) + 1)
            DirPath(UBound(DirPath)) = RootPath & RetVal & "\"
            RetVal = Dir()
        End If
    Loop
    'Loop through directories+files
    For i = 1 To UBound(DirPath)      'directories
        RootPath = DirPath(i)
        AFile = Dir(RootPath & "*.*")   'get first file
        Debug.Print: Debug.Print Now
        Do
            'Please note I wish to keep Ad*.*, Bv*.*, and La*.*
            'test the filename
            Select Case UCase(Left(AFile, 2))
            Case Is = "AD", "BV", "LA"
                Debug.Print "Leaving " & RootPath & AFile
            Case Else
                Debug.Print "Deleting " & RootPath & AFile
                If Not TestMode Then
                    Kill RootPath & AFile      'Delete File
                End If
            End Select
            AFile = Dir()                   'Get next file
        Loop While AFile <> ""              'go until no files
    Next i    '/directory
End Sub
 
Upvote 0
Hi Tweedle

As you have rightly said, your first code is working perfectly OK. Perhaps because I made the following changes in the code, it might have lead to wrong results. "AD" to "Ad", "BV" to "Bv", and "LA" to "La". I had made these changes to comply with the actual file names.

As regards the second code, when I run the same, there seems to be no action of any kind. All the files are just intact in the subfolders. In this code, I did not make any changes. Please look into the matter.

Thanks.
 
Last edited:
Upvote 0
For the second version to enact on files, set
Const TestMode = False.

Changing the first version from upper case to mixed case would make a difference, failing the test and deleting the file as no upper case "UCase" string could be equal to a mixed case string. Anyway; change Const TestMode = True to Const TestMode = False and you should be good to go.
 
Upvote 0
Thank you so much. The second code is now working fine. I am so dumb, you had already written in the code itself "True suppresses file-deletion; False processes file-deletion" but I failed to notice that. So sorry for this silly mistake.

Thanks once again!
 
Upvote 0

Forum statistics

Threads
1,223,911
Messages
6,175,337
Members
452,637
Latest member
Ezio2866

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