VBA Delete File

VBA Delete File

VBA Delete File from a folder or directory in Excel. 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 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
  • Please have a check specified folder before and after running macro.
  • After running macro the specified folder deletes specified file.

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 *