VBA Delete File in Excel

VBA Delete File

VBA Delete File in Excel from a folder or directory. You can delete any file like Excel, Word, PowerPoint, CSV, Notepad etc. Let us see different examples in the following tutorial. We are using Kill statement to delete a file.

Example on VBA Delete File

Let us see an example how to delete a file in Excel using VBA. The following example helps to delete an Excel file.

'VBA Delete Excel File
Sub VBAF1_Delete_File()
    
     'Variable declaration
    Dim sFolderPath As String
    Dim sFileName As String
    
    'Define Folder Path and file name
    sFolderPath = "C:\VBAF1\Test\"
    sFileName = "sample.xlsx"
    
    'Delete Excel file
    Kill sFolderPath & sFileName
    
End Sub

Note:You can check your output by creating sample file in specified folder before and after running macro.

The following macro helps to delete Word document file.

'VBA Delete Word File
Sub VBAF1_Delete_File()
    
     'Variable declaration
    Dim sFolderPath As String
    Dim sFileName As String
    
    'Define Folder Path and file name
    sFolderPath = "C:\VBAF1\Test\"
    sFileName = "Documentation.docx"
    
    'Delete Word file
    Kill sFolderPath & sFileName
    
End Sub

The following VBA code helps to delete CSV file.

'VBA Delete CSV File
Sub VBAF1_Delete_File()
    
     'Variable declaration
    Dim sFolderPath As String
    Dim sFileName As String
    
    'Define Folder Path and file name
    sFolderPath = "C:\VBAF1\Test\"
    sFileName = "Documentation.csv"
    
    'Delete CSV file
    Kill sFolderPath & sFileName
    
End Sub

Example on Deleting a file using VBA FSO Object

Let us an example VBA macro code to delete Excel file using VBA FileSystemObject (FSO) in Excel.

'VBA Delete Excel File using VBA FileSystemObject object in Excel.
Sub VBAF1_Delete_File_Using_FSO()
    
     'Variable declaration
    Dim sFolderPath As String
    Dim sFileName As String, oFSO As FileSystemObject
    
    'Define Folder Path and file name
    sFolderPath = "C:\VBAF1\Test\"
    sFileName = "sample.xlsx"
    
     'Create FSO Object
    Set oFSO = CreateObject("Scripting.FileSystemObject")
    
    'Delete file
    oFSO.DeleteFile sFolderPath & sFileName, True
    
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