I have a large collection of files (many thousands) and I only want to keep those containing a certain string in its filename (that is, "10-K".) Here is a picture of what I want do to -- except for those files containing "10_K" in the file name, delete the others. (This is a sampling of the directory -- there are many thousands of files in the entire folder.)
I cooked up a process for the time being but it is VERY tedious --
I used VBA to list all the file names in the folder. Then I used a "_" delimiter to parse the filename. Then I filtered out the files I wanted to delete, used a cell reference to fill in the absolute reference for the files, and then another macro to delete those files.
Here is the code for that...
YIKES!
I cooked up a process for the time being but it is VERY tedious --
I used VBA to list all the file names in the folder. Then I used a "_" delimiter to parse the filename. Then I filtered out the files I wanted to delete, used a cell reference to fill in the absolute reference for the files, and then another macro to delete those files.
Here is the code for that...
YIKES!
Code:
Sub ListAllFile()
'Source: http://www.ozgrid.com/forum/showthread.php?t=65530
Dim objFSO As Object
Dim objFolder As Object
Dim objFile As Object
Dim ws As Worksheet
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set ws = Worksheets.Add
'Get the folder object associated with the directory
Set objFolder = objFSO.GetFolder("C:\QTR2")
ws.Cells(1, 1).Value = "The files found in " & objFolder.Name & "are:"
'Loop through the Files collection
For Each objFile In objFolder.Files
ws.Cells(ws.UsedRange.Rows.Count + 1, 1).Value = objFile.Name
Next
'Clean up!
Set objFolder = Nothing
Set objFile = Nothing
Set objFSO = Nothing
End Sub
Sub DelFiles()
'Source: https://www.mrexcel.com/forum/excel-questions/777009-visual-basic-applications-delete-files-selected-ranges.html
Dim blnDelAll As Boolean
Dim rngVal As Range
Dim rngCl As Range
Set rngVal = Columns("A").SpecialCells(xlCellTypeConstants)
On Error Resume Next
For Each rngCl In rngVal.Cells
Kill rngCl.Value
If Err.Number <> 0 Then
Err.Clear
rngCl.Offset(, 1) = "File not found"
blnDelAll = True
End If
Next
On Error GoTo 0
If blnDelAll Then
MsgBox "Some File were not deleted, invalid path or you do not have permission to delete this file."
Else
MsgBox "All Files successfully deleted."
End If
End Sub