How to delete files and folders automatically using the File System Object (FSO) in VBA. Watch the video below:
We will learn how to delete files and folders using FSO or File System Object in VBA. The File System Object or FSO allows us to access the file system on our computer. We will use ‘late-binding‘ and will therefore not reference the Microsoft Scripting Runtime Object Library.
Below is given the code to delete all Excel files from a specific folder:
Sub DeleteAllExcelFilesFromFolder()
Dim fso As Object
Set fso = CreateObject(“Scripting.FileSystemObject”)
fso.deletefile “C:\test-folder-delete-files*.xl*”
End Sub
If we wanted to delete all the files from a folder , we would use the following code:
Sub DeleteAllFilesFromFolder()
Dim fso As Object
Set fso = CreateObject(“Scripting.FileSystemObject”)
fso.deletefile “C:\test-folder-delete-files*.*”
End Sub
If we wish to delete the complete folder, we can use the following code:
Sub DeleteFolder()
Dim fso As Object
Set fso = CreateObject(“Scripting.FileSystemObject”)
fso.DeleteFolder “C:\test-folder-delete-files”
End Sub
In this manner we can delete files and folders from our computer using FSO in VBA.
