Excel VBA Remove Empty Directories

Hello,

I need help with a VBA code.  to give me an option to select a directory and then search within that directory all folders and sub folders if any folder found empty then delete and resume next.


thanks.
LVL 6
FloraAsked:
Who is Participating?
 
Rgonzo1971Commented:
HI,

pls try

Sub Macro()
DeleteEmptyFolders "c:\TestFolder"
End Sub

Public Sub DeleteEmptyFolders(ByVal strFolderPath As String)
  
   Set oFSO = CreateObject("Scripting.FileSystemObject")
   If Not oFSO.FolderExists(strFolderPath) Then Exit Sub
   
   Set oFolder = oFSO.GetFolder(strFolderPath)
   
   On Error Resume Next
   
   If oFolder.SubFolders.Count > 0 Then
        lngFolder = 1
        ReDim strPaths(1 To oFolder.SubFolders.Count)

        For Each fsoSubFolder In oFolder.SubFolders
            strPaths(lngFolder) = fsoSubFolder.Path
            lngFolder = lngFolder + 1
        Next fsoSubFolder
        
        lngSubFolder = 1
        Do While lngSubFolder < lngFolder
           Call DeleteEmptyFolders(strPaths(lngSubFolder))
           lngSubFolder = lngSubFolder + 1
        Loop
    End If
   
    If oFolder.Files.Count = 0 And oFolder.SubFolders.Count = 0 Then
        oFolder.Delete
    End If
End Sub

Open in new window

Regards
0
 
FloraAuthor Commented:
sweet Rgonzo1971

thanks very much
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.