You are on page 1of 2

Delete files and folders Important ! Read this page from Chip Pearson first http://www.cpearson.com/excel/Recycle.

htm From Chip's site : You need to remember, though, that Kill permanently deletes the file. There is no way to "undo" the delete. The file is not sent to the Windows Recycl e Bin ( Same for the macro's that use the filesystemobject ) Sub DeleteExample1() 'You can use this to delete all the files in the folder Test On Error Resume Next Kill "C:\Users\Ron\Test\*.*" On Error GoTo 0 End Sub Sub DeleteExample2() 'You can use this to delete all xl? files in the folder Test On Error Resume Next Kill "C:\Users\Ron\Test\*.xl*" On Error GoTo 0 End Sub Sub DeleteExample3() 'You can use this to delete one xls file in the folder Test On Error Resume Next Kill "C:\Users\Ron\Test\ron.xls" On Error GoTo 0 End Sub Sub DeleteExample4() 'You can use this to delete the whole folder 'Note: RmDir delete only a empty folder On Error Resume Next Kill "C:\Users\Ron\Test\*.*" ' delete all files in the folder RmDir "C:\Users\Ron\Test\" ' delete folder On Error GoTo 0 End Sub Sub Delete_Whole_Folder() 'Delete whole folder without removing the files first like in DeleteExample4 Dim FSO As Object Dim MyPath As String Set FSO = CreateObject("scripting.filesystemobject") MyPath = "C:\Users\Ron\Test" '<< Change If Right(MyPath, 1) = "\" Then MyPath = Left(MyPath, Len(MyPath) - 1) End If If FSO.FolderExists(MyPath) = False Then MsgBox MyPath & " doesn't exist" Exit Sub End If

FSO.deletefolder MyPath End Sub Sub Clear_All_Files_And_SubFolders_In_Folder() 'Delete all files and subfolders 'Be sure that no file is open in the folder Dim FSO As Object Dim MyPath As String Set FSO = CreateObject("scripting.filesystemobject") MyPath = "C:\Users\Ron\Test" '<< Change If Right(MyPath, 1) = "\" Then MyPath = Left(MyPath, Len(MyPath) - 1) End If If FSO.FolderExists(MyPath) = False Then MsgBox MyPath & " doesn't exist" Exit Sub End If On Error Resume Next 'Delete files FSO.deletefile MyPath & "\*.*", True 'Delete subfolders FSO.deletefolder MyPath & "\*.*", True On Error GoTo 0 End Sub

You might also like