Microsoft Excel
Back to jkp-ads.com

Ron de Bruin
Excel Automation

Microsoft MVP Program

Delete files and folders

Important message to visitors of this page

Ron de Bruin decided to remove all Windows Excel content from his website for personal reasons. If you want to know why, head over to rondebruin.nl.

Luckily, Ron was kind enough to allow me to publish all of his Excel content here.

Most of these pages are slightly outdated and may contain links that don 't work. Please inform me if you find such an error and I'll try to fix it.

Kind regards

Jan Karel Pieterse


Be aware that Kill permanently deletes the file. There is no way to "Undo" the delete, the file is not sent to the Windows Recycle 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

If you want to move your files to the Windows Recycle Bin check out this webpage from Chip Pearsonhttp://www.cpearson.com/excel/recycle.aspx