DelTree
Skip Navigation Links.

DelTree

Skip Navigation LinksHome :: Visual Basic :: Delete Directory

Here's a simple Visual Basic function you can use in Vb6+/MS Access to delete directories and sub directories (like the DOS command of the same name).

Call like this: DelTree("C:\DATA\MYDIR")
Also requires: File Errors (error handler)

Warning - Once deleted, it's gone!

Function DelTree(strDirectory As String) As Boolean

    ' Deletes an entire directory tree (including all
    ' files and subdirectories). Calls itself recursively.
    
    ' In:
    ' strDirectory
    ' Directory to delete.
    ' Out:
    ' Return Value:
    ' True if successful, False if not.
    ' Example:
    ' Call DelTree("C:\") ' Ha! Ha! Just kidding
    ' Call DelTree("C:\DATA\MYDIR")

    On Error GoTo HandleError

    Dim StrOriginalDir As String
    Dim strFileName As String
        
    'make sure that you never delete C directory!
    If strDirectory = "C:\" Then
        Exit Function
    End If
    
    ' Check to make sure the directory actually exists.
    ' If not, we don't have to do a thing.
    If Len(Dir(dhFixPath(strDirectory), vbDirectory)) = 0 Then
        Exit Function
    End If
    
    
If MsgBox("Delete " & strDirectory & " ?", vbYesNo, "Delete Directory") = vbYes Then
    ' Store original directory and change to one
    ' to be removed
    StrOriginalDir = CurDir
    ChDir strDirectory
  
    ' Delete all the files in the current directory
    strFileName = Dir("*.*")
    Do Until strFileName = ""
        Kill strFileName
        strFileName = Dir
    Loop
    
    ' Now build a list of subdirectories
    Do
        strFileName = Dir("*.*", vbDirectory)
        
        ' Skip "." and ".."
        Do While strFileName = "." Or strFileName = ".."
            strFileName = Dir
        Loop
    
        ' If there are no more files, exit the loop
        ' otherwise call DelTree again to wipe
        ' out the subdirectory
        If strFileName = "" Then
            Exit Do
        Else
            If Not DelTree(strFileName) Then
                GoTo ExitHere
            End If
        End If
    Loop
    
    ' Change back to the original directory
    ChDir StrOriginalDir
    
    ' Finally, remove the target directory
    RmDir strDirectory
    DelTree = True
End If
    
ExitHere:
    Exit Function
HandleError:
    Select Case Err.Number
        Case Else
            MsgBox Err.Description, vbExclamation, _
             "Error " & Err.Number & " in DelTree"
        Resume ExitHere
    End Select
End Function

Copy and paste the Visual Basic code below into your module

Please Link to us Next >> Make Directory
top of page
all content ©1996/2012 BennySutton.com
all images © their respective owners This site uses Thumbshots previews