Excel VBA Delete Folder if Exists

Delete Folder using Excel VBA Macro

This Excel VBA code will get folder path as input, check if it exists. Then it will delete if it exists.

Important Note: Do not test this code with any important folder in your computer. You will end up in deleting important files in the folder.

There are 2 possible methods available to do this:

  1. FSO.DeleteFolder
  2. VBA.RMDir

Create a dummy folder & give its path as input.  Now, here is the code.

Sub vbaDeleteFolder(sFolderPath As String)
    'Add Reference to 'Microsoft Sripting Runtime
    Dim fso As FileSystemObject
    Set fso = New FileSystemObject
    
    'Delete Folder using FSO Object
    If fso.FolderExists(sFolderPath) Then
        fso.DeleteFolder sFolderPath
    End If
    
    'Delete Using VBA Command
    If VBA.Dir(sFolderPath, vbDirectory) <> "" Then
        VBA.RmDir sFolderPath
    End If
End Sub

Once the code is executed the test folder will be deleted permanently. You cannot find the folder in Trash/Recycle bin also.

Delete List of Folders Matching a Pattern

The main difference between the above 2 methods is that, the FSO object can take wild card matching for folder. VBA Rmdir needs exact path.

So, to delete a list of files with specific pattern, fso object can be used a below.

     fso.DeleteFolder "E:\A1*"

Be it any method, the folders & the files within them will be permanently deleted.

To Read More on FSO Object Reference – Click here.

External Reference on RmDir command from Microsoft – Click here.