DreamDancer

DeleteEmptyFolders

Feb 24th, 2013
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ' !!! !!! !!! !!! !!! WARNING !!! !!! !!! !!! !!!
  2. ' This is dangerous code, if not done right, it will delete files from your hard drive
  3. ' until it runs into an error from trying to delete something that can't be deleted
  4. ' !!! !!! !!! !!! !!! WARNING !!! !!! !!! !!! !!!
  5.  
  6. ' This is supposed to only delete empty folders that contain no files
  7.  
  8. Sub DeleteEmptyFolders()
  9. Dim FSO As Object, FSF As Object, FSS As Object, SF As Object
  10.  
  11.   Set FSO = CreateObject("Scripting.FileSystemObject")
  12.   RecurseFolders "%START-PATH%" ' replace this with your target for assassination.
  13. End Sub
  14.  
  15.  
  16. Function RecurseFolders(FolderPath As String) As Long
  17. Dim FSO As Object, FSF As Object, FSS As Object, SF As Object, Results As Long
  18.  
  19.   Set FSO = CreateObject("Scripting.FileSystemObject")
  20.   Set FSF = FSO.GetFolder(FolderPath)
  21.  
  22.   Set FSS = FSF.SubFolders
  23.   If (FSS.Count = 0) Then
  24.     Results = FSF.Files.Count
  25.   Else
  26.     For Each SF In FSS
  27.       Results = RecurseFolders(FolderPath & "\" & SF.Name)
  28.       If (Results = 0) Then
  29.         FSO.DeleteFolder FolderPath & "\" & SF.Name
  30.         Results = 0
  31.       Else
  32.         Exit For
  33.       End If
  34.     Next
  35.   End If
  36.  
  37.   RecurseFolders = Results
  38. End Function
Advertisement
Add Comment
Please, Sign In to add comment