excel vba‎ > ‎

VBA - Delete files and folders

posted Feb 4, 2011, 8:21 AM by Roberto Felicini
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 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:\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\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\Test\aa.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\a\Test\*.*"    ' delete all files in the folder
    RmDir "C:\Users\a\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\a\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\a\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
Comments