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" Else 'Display Message MsgBox "Specified directory doesn't exists.", vbInformation, "VBAF1" End If End Sub
Output: You can find following output for your reference.
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
- Now you can specified directory. It has deleted and displayed message.
- If specified directory is not available, then it displays message.
Related Articles
You can also learn complete details like syntax, example and etc by clicking on the following buttons.