Delete a directory and its contents (files, subdirectories) without using FileSystemObject

I want to know if this code snippet can be rewritten:

Private Sub PrepareDir(ByVal dir As String)
    Dim fso As New FileSystemObject
    If fso.FolderExists(dir) Then Call fso.DeleteFolder(dir, True)
    Call fso.CreateFolder(dir)
End Sub

With VBA statements: Kill, MkDir, etc. The most difficult part of this is to delete a non-empty directory. With FSO, this can be done easily, but how can this be done without FSO?

+4
source share
1 answer

This piece of code uses RmDir to delete the Mailbox. AFAIK, RmDir cannot delete a folder if it is not empty, so first clear the contents in the folder, then delete the directory.

Private Sub PrepareDirModified(dirStr As String)
On Error Resume Next
    If Right(dirStr, 1) <> "\" Then dirStr = dirStr & "\"
    Kill dirStr & "*.*" 
    RmDir dirStr
    MkDir dirStr
On Error GoTo 0
End Sub

Hope this helps.

+6
source

All Articles