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 .
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
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]
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.