Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Delete a folder and all subfolders and files

File System

Delete a folder and all subfolders and files

by  zollo9999  Posted    (Edited  )
Here is a simple method to delete a folder and all files and subfolders. It uses the File system Object. To use it, you will have to set a reference to the 'Microsoft Scripting Runtime' usually found at C:\WINDOWS\system32\scrrun.dll .


Code:
Public Sub DeleteAllFolders(FolderPath As String)

   Dim fso As Scripting.FileSystemObject
   Set fso = New Scripting.FileSystemObject
  
   On Error Resume Next
   fso.DeleteFolder (FolderPath)
   Set fso = Nothing

End Sub

The fso.DeleteFolder method cannot take a trailing "\" in the path so the following code will remove it. [This can be called before inserting the FolderPath parameter or inside the DeleteAllFolders sub before fso.DeleteFolder]

Code:
Function CorrectPath(FolderPath As String) As String
'If FolderPath has trailing backslash, remove it.
    
    FolderPath = Trim(FolderPath)
    If Right(FolderPath, 1) = "\" Then
        CorrectPath = Left(FolderPath, Len(FolderPath) - 1)
    Else
        CorrectPath = FolderPath
    End If
End Function

READ ONLY Files
If any file/document in the folder has the Read-Only attribute set, DeleteFolder will fail with Error 70 Permission Denied. You will have to clear the attribute or delete the file manually.

Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top