These VBA macros delete files of one type from a folder, such as old .tmp or .bak files, or remove a whole folder. Both ask you to confirm first, because files deleted this way don’t go to the Recycle Bin.
Works inExcel 2010 and later, Windows and Mac
UndoNot possible. Save a copy first
Save asMacro-Enabled Workbook (.xlsm)
New to macros? See how to use the macros on this site: copy the code, paste it into a module with Alt + F11, and run it with Alt + F8.
Table of Contents
Delete files of one type
Sub DeleteFilesOfType()
Dim p As String, t As String
With Application.FileDialog(msoFileDialogFolderPicker)
If .Show = 0 Then Exit Sub
p = .SelectedItems(1) & Application.PathSeparator
End With
t = InputBox("Delete files matching, for example *.tmp or *.bak:", , "*.tmp")
If t = "" Then Exit Sub
If Dir(p & t) = "" Then MsgBox "No matching files.": Exit Sub
If MsgBox("Permanently delete " & t & " in" & vbLf & p & "?", vbYesNo + vbExclamation) = vbNo Then Exit Sub
Kill p & t
End Sub
Kill deletes every file matching the pattern in that folder (not in subfolders).
Delete a folder and everything in it
Sub DeleteFolder()
Dim p As String
With Application.FileDialog(msoFileDialogFolderPicker)
If .Show = 0 Then Exit Sub
p = .SelectedItems(1)
End With
If MsgBox("Permanently delete this folder and ALL its contents?" & vbLf & p, vbYesNo + vbCritical) = vbNo Then Exit Sub
CreateObject("Scripting.FileSystemObject").DeleteFolder p, True
End Sub
True also deletes read-only files. This uses Windows’ FileSystemObject, so it works on Windows only.
Delete one file
Sub DeleteOneFile()
Dim f As Variant
f = Application.GetOpenFilename()
If f = False Then Exit Sub
If MsgBox("Delete " & f & "?", vbYesNo) = vbYes Then Kill f
End Sub
Things to know
- Deleted files don’t go to the Recycle Bin. Test on a copy of the folder first.
- Files that are open, in Excel or elsewhere, can’t be deleted and cause an error.
- Keep the confirmation messages in. They’re your last chance to stop a mistake.