VBA Delete All Files in a Folder

VBA Delete All Files in a Folder

VBA Delete All Files in a Folder in Excel Delete all Files in a Folder in Excel using VBA. If folder is empty, then no file is available to delete. In the following tutorial we have explained with example and step by step instructions for user reference.

VBA Delete All Files in a Folder

Let us see an example VBA macro code to deleting all files in a folder in Excel. Here you can see different methods. We are using Kill statement and FSO object.
Method 1: Using FileSystemObject Object

'VBA Delete All Files in a Folder
Sub VBAF1_Delete_All_Files_in_a_Folder()

    'Variable declaration
    Dim sFolderPath As String
    Dim sFileName As String, oFile As Object
    
    'Define Folder Path
    sFolderPath = "C:\VBAF1\Test\"
   
    'Create FSO Object
    Set oFSO = CreateObject("Scripting.FileSystemObject")
    
    'Check Specified Folder exists or not
    If oFSO.FolderExists(sFolderPath) Then
        'Loop through each file in a specified folder
        For Each oFile In oFSO.GetFolder(sFolderPath).Files
            'Delete Each File
            oFile.Delete
        Next
     End If

End Sub

Note: You can have a check specified folder before and after running macro. After running macro all files are deleted from the folder.

Method 2: Using FSO Object Delete All Files in a Folder

We can see here how to Delete All Files in a Folder using FSO object.

'VBA Delete All Files in a Folder
Sub VBAF1_Delete_All_Files_in_a_Folder_Using_FSO()

    'Variable declaration
    Dim sFolderPath As String
    Dim sFileName As String, oFile As Object
    
    'Define Folder Path
    sFolderPath = "C:\VBAF1\Files and Folders\"
    
    'Create FSO Object
    Set oFSO = CreateObject("Scripting.FileSystemObject")
   
    'Delete All Files in a folder
    oFSO.DeleteFile sFolderPath & "\*.*", True

End Sub

Method 3: Using Kill Statement Delete All Files in a Folder

Let us see how to delete Delete All Files in a Folder using Kill statement.

'VBA Delete All Files in a Folder
Sub VBAF1_Delete_All_Files_in_a_Folder_Using_Kill()

    'Variable declaration
    Dim sFolderPath As String
    
    'Define Folder Path
    sFolderPath = "C:\VBAF1\Files and Folders\"
   
    'Delete All Files in a folder
    Kill sFolderPath & "\*.*"

End Sub

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