VBA Delete all Files and Subfolders form a folder using Excel VBA. You can delete all files using DeleteFile method of FileSystemObject. And delete all folders using DeleteFolder method of FileSystemObject.
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 creating sample files and sub-folders in the specified folder. Run above macro. Once you run above VBA code the folder becomes empty. There are no files or sub-folders in it.
You can refer the following link for the step by step instructions.
Click on the following links of the useful resources. These helps to learn and gain more knowledge.