Delete Files Using VBA (With Examples) How to use VBA to delete files

VBA (Visual Basic for Applications) is a programming language that can be used to automate and simplify tasks in Microsoft applications, such as Excel and Access. One way to use VBA is to delete files. This can be done with the VBA Kill command, which will permanently delete the specified file from the computer. Example code for the VBA Kill command can be found online, and it can be modified to fit specific needs. Additionally, the VBA Dir command can be used to search for a list of files that match a certain criteria before the VBA Kill command is used to delete them.


You can use the Kill statement in VBA to delete a specific Excel file in a specific folder.

Here is one common way to use this statement in practice:

Sub DeleteFile()

    On Error Resume Next
    Kill "C:UsersBobDesktopMy_Datasoccer_data.xlsx"
    On Error GoTo 0

End Sub

This particular macro deletes the Excel file called soccer_data.xlsx located in the following folder:

C:UsersBobDesktopMy_Data

The line On Error Resume Next tells VBA that if an error occurs and the file is not found that no error message should be shown.

We then use On Error GoTo 0 to reset the default error message settings.

If you would like to display an error message if the file is not found, then simply remove these two lines from the code.

The following example shows how to use this syntax in practice.

Example: Delete File Using VBA

Suppose we have the following folder with three Excel files:

Suppose we would like to use VBA to delete the file called soccer_data.xlsx.

We can create the following macro to do so:

Sub DeleteFile()

    On Error Resume Next
    Kill "C:UsersBobDesktopMy_Datasoccer_data.xlsx"
    On Error GoTo 0

End Sub

Once we run this macro and open the folder again, we will see that the file called soccer_data.xlsx has been deleted:

If you would like an error message to be shown if the file doesn’t exist, you can use the following macro instead:

Sub DeleteFile()

    Kill "C:UsersBobDesktopMy_Datasoccer_data.xlsx"

End Sub

When we run this macro, we receive the following error message:

We receive this error message because the file soccer_data.xlsx has already been deleted and no longer exists in the folder.

Note: Be aware that the Kill statement permanently deletes a file and does not simply send it to the recycling bin.

x