VBA Delete All Files in a Folder

VBA Delete All Files in a Folder

Deleting all Files in a Folder in Excel using VBA. If folder is empty, then no file is avilable 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

'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

'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 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
  • You can have a check specified folder before and after running macro
  • After running no file will be available in the folder.

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

Your email address will not be published. Required fields are marked *