Delete all files in a folder even if empty

esposit513

New Member
Joined
Nov 9, 2011
Messages
5
I wrote code as part of an excel macro to delete all files in a folder but sometimes get an error if the folder is empty. how can i modify this to delete all files and not get an error
Kill "S:\Reporting Center*.pdf"


The macro repeats this line of code for about 15 different folders. When i first created the macro it worked fine but now it isn't. i get a debug error and i believe it is because the folder is empty. If the folder is empty i want the macro to just move on to the next line of code and empty the next folder.
 

Excel Facts

Do you hate GETPIVOTDATA?
Prevent GETPIVOTDATA. Select inside a PivotTable. In the Analyze tab of the ribbon, open the dropown next to Options and turn it off
Code:
Dim OfsObj as Object
Set OfsObj = CreateObject("Scripting.FilesystemObject")
OfsObj.deletefolder ("C:\" &  FolderName)
Set OfsObj = Nothing
HTH. Dave
edit: whoops U don't want to remove folder...only all files and keep folder. Will post again.
 
Last edited:
Upvote 0
Trial 2.
Code:
Sub test3()
Dim fso As Object, FlDr As Object, Fl As Object
Set fso = CreateObject("scripting.filesystemobject")
'***change Folder name (ie.Datafiles2) to your folder name
Set FlDr = fso.GetFolder(ThisWorkbook.Path & "\Datafiles2")
For Each Fl In FlDr.Files
If Right(Fl.Name,3) = "pdf" Then
Kill Fl.Path
End If
Next Fl
Set FlDr = Nothing
Set fso = Nothing
End Sub
 
Upvote 0
Maybe
Code:
if Dir("S:\Reporting Center*.pdf") <> "" Then Kill "S:\Reporting Center*.pdf"
 
Upvote 0

Forum statistics

Threads
1,213,526
Messages
6,114,136
Members
448,551
Latest member
Sienna de Souza

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