VBA Delete Files from Folder

This VBA will NOT permanently delete the files from folder. It will delete the files to the Recycle bin so if needed the files can still be restored.

The below macro you need to set your Filepath (strpath), Drive letter (ChDrive), filetype (strextend) and search word term (fName).  fName is the term the macro will check for and any filename containing that word will be deleted.

VBA Delete Files from Folder

Dim strpath, strextend, sFile As String
Dim FSO

'Set your folder path 
strpath = "Z:\Downloads"
If Right(strpath,1)<>"\" then strpath = strpath + "\"
'Set the Drive your folder is in
ChDrive "Z:\"
ChDir strpath
'Set the delete file name for the macro to check for.  Any filename containing word "Files" will be deleted
fName = "Files"
'Set file extension for files to delete, can use *.* for any filetype
strextend = Dir("*.xls*")
Do While strextend <> ""
  If instr(1,strextend,fName,vbTextCompare)>0 Then
    sFile = strpath & strextend
    Set FSO = CreateObject("Scripting.FileSystemObject")
    If FSO.FileExists(sFile) Then
       FSO.DeleteFile sFile, True
    End If
  End If
strextend = Dir
Loop

Interested in learning new skills?