Macro to Delete Specified Files in a Folder

howard

Well-known Member
Joined
Jun 26, 2006
Messages
6,563
Office Version
  1. 2021
Platform
  1. Windows
I have the following code to delete specified files in a folder

Code:
 Sub Delete_Files()


mypath = Sheets("Delete Old EMTQ Files").Range("A2") & "\"
On Error Resume Next
For Each cl In Sheets("Delete Old EMTQ Files").Range("C2", Sheet1.Range("C" & Sheets("Delete Old EMTQ Files").Rows.Count).End(xlUp))
    With CreateObject("Scripting.filesystemObject")
        For Each sf In .GetFolder(mypath).Files
            If UCase(sf.Name) Like "*" & UCase(cl.Value) & "*" Then Kill sf
        Next
    End With
Next

End Sub


I have set up the Folder Path in A2, No for subfolder in B2 and *EMTQ* in C2 for file name

I get subscript out of range when running macro and code below is highlighted

Code:
 mypath = Sheets("Delete Old EMTQ Files").Range("A2") & "\"


It would be appreciated if someone could kindly amend my code



 

Excel Facts

Select all contiguous cells
Pressing Ctrl+* (asterisk) will select the "current region" - all contiguous cells in all directions.
I get subscript out of range when running macro and code below is highlighted

Code:
mypath = Sheets("Delete Old EMTQ Files").Range("A2") & "\"
That usually means that it cannot find a sheet name "Delete Old EMTQ Files".
Check to make sure that the sheet really exists, and that is the EXACT name.
Any extra spaces or characters will cause it not to match.
 
Upvote 0
Thanks Joe. There was a at the end of the sheet name
 
Upvote 0
You are welcome.
 
Upvote 0

Forum statistics

Threads
1,215,222
Messages
6,123,716
Members
449,116
Latest member
Aaagu

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