Delete empty folders

User avatar
Abraxus
3StarLounger
Posts: 254
Joined: 01 Mar 2010, 17:34
Location: Blue Springs, MO

Delete empty folders

Post by Abraxus »

I have code that will delete all files & folders in a given directory:

Code: Select all

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 = CurrentDBDir & "Reports"  '<< 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
What I need now is code that will only delete the EMPTY folders.

I've tried a few I've found online, but none seem to work properly...

Any suggestions?
Morgan

User avatar
HansV
Administrator
Posts: 78545
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Delete empty folders

Post by HansV »

This is air code, I haven't actually tested it:

Code: Select all

    'Delete subfolders
    Dim fld As Object
    Dim i As Long
    Set fld = fso.GetFolder(MyPath)
    For i = fld.SubFolders.Count To 1 Step -1
      If fld.SubFolders(i).Files.Count = 0 And fld.SubFolders(i).SubFolders.Count = 0 Then
        fld.SubFolders(i).Delete
      End If
    Next i
Best wishes,
Hans