VBA Remove Directory and its Content

VBA Remove Directory and its Content

VBA Remove specified directory and its content. In the following tutorial we have explained step by step instructions to run example macro.

VBA Remove Directory and its Content

Let us see an example macro VBA code to removing specified directory and its content. In the below example we are specifying root folder path as ‘C:\VBAF1\’. You can change this path according to your requirement. In the below example we use ‘DeleteFile’ method of FSO to remove all available files from a specified folder. And used ‘DeleteFolder’ method of FileSystemObject object to remove all available subfolders from a specified directory.

'VBA Removing specified Directory and its Content
Sub VBAF1_Remove_Directory_and_its_Content()
    'Variable declaration
    Dim sFolderPath As String, oFSO as Object
    Dim oFSO As FileSystemObject
     'Define Folder Path
    sFolderPath = "C:\VBAF1\"
    'Check if slash is added
    If Right(sFolderPath, 1) = "\" Then
        'If added remove it from the specified path
        sFolderPath = Left(sFolderPath, Len(sFolderPath) - 1)
    End If
    'Create FSO Object
    Set oFSO = CreateObject("Scripting.FileSystemObject")
    'Check Specified Folder exists or not
    If oFSO.FolderExists(sFolderPath) Then
        'Delete All Files
        oFSO.DeleteFile sFolderPath & "*.*", True
        'Delete All Subfolders
        oFSO.DeleteFolder sFolderPath & "*.*", True
        'Display Message
        MsgBox "Specified directory has deleted.", vbInformation, "VBAF1"
        'Display Message
        MsgBox "Specified directory doesn't exists.", vbInformation, "VBAF1"
    End If
End Sub

Output: You can find following output for your reference.
VBA Remove Directory and its Content

Instructions to Run VBA Macro Code or Procedure:

You can refer the following link for the step by step instructions.

Instructions to run VBA Macro Code

Other Useful Resources:

Click on the following links of the useful resources. These helps to learn and gain more knowledge.

VBA Tutorial VBA Functions List VBA Arrays VBA Text Files VBA Tables

VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers Blog

Leave a Comment