VBA Delete All Files and Subfolders

VBA Delete All Files and Subfolders

VBA Delete all Files and Subfolders form a specified folder using Excel VBA. You can delete all files using DeleteFile method of FileSystemObject. And delete all folders using DeleteFolder method of FileSystemObject.

VBA Delete All Files and Subfolders from a Folder

Let us see how to delete files and sub-folders from a folder using VBA in Excel. The following VBA macro code helps to delete all files and sub-folders. We are using DeleteFile and DeleteFolder methods of FileSystemObject. In the below macro you can change the specified path as per your requirement. The following macro we used “\*.*” in DeleteFile method. It represents all files in a specified folder. It can be any type of file. And also we used “\*.*” in DeleteFolder method. It represents all folders in a specified folder.

'VBA Deleting All Files and Subfolders
Sub VBAF1_Delete_All_Files_and_Subfolders()
    'Variable declaration
    Dim sFolderPath As String
    Dim oFSO As FileSystemObject
     'Define Folder Path
    sFolderPath = "C:\VBAF1\Test\"
    '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
     End If
End Sub

Note:You can check your output by creting sample files anf subfolders in the specified folder. Run above macro. Once you run above VBA code the folder becomes empty. There are no files or subfolders in it.

Instructions to use VBA Macro Code

Here are the instructions to use above macro in Visual basic editor.

  • Open Visual Basic Editor(VBE) by clicking Alt +F11
  • Go to code window by clicking F7
  • Copy above specified macro or procedure
  • Paste above copied code in code window
  • Run macro by clicking F5 or Run command
  • Please have a check specified folder before and after running macro.
  • After running macro the specified folder is empty. There are no files or subfolders in it.

Related Articles

You can also learn complete details like syntax, example and etc by clicking on the following buttons.

VBA File and Directory Functions in Excel Related Posts

Leave a Comment