To delete a file using VBA, use the Kill statement followed by the full path and filename of the target file (e.g., Kill "C:\Folder\file.txt"). This command permanently removes the specified file from the local drive or network share without sending it to the Recycle Bin. Before running this code, you must ensure that the file exists and is not currently open in another application, otherwise, VBA will trigger a runtime error.
What You'll Need
- A Windows PC with Microsoft Excel, Word, or Access installed.
- The Visual Basic for Applications (VBA) editor (built into Microsoft Office).
- The exact file path and file extension (e.g., .xlsx, .txt, .pdf) of the file you wish to delete.
- Administrative permissions to modify or delete files in the target folder.
Step-by-Step
- Open the VBA Editor: Launch your Microsoft Office application. Press
Alt + F11on your keyboard to open the Visual Basic Editor window. - Insert a New Module: In the Project Explorer pane on the left, right-click on your workbook or document name. Select
Insertand then clickModule. This creates a blank space where you can write your custom code. - Declare the File Path Variable: It is best practice to store the file path in a variable rather than hard-coding it directly into the Kill statement. This makes the code easier to update. Type the following:
Dim filePath As String. - Assign the Path: Set the variable to the full location of your file. For example:
filePath = "C:\Users\YourName\Documents\OldReport.xlsx". Ensure you use double backslashes if you are concatenating strings or be mindful of the exact string format. - Implement a File Existence Check: Running the
Killcommand on a file that does not exist will cause the program to crash. Use theDirfunction to verify the file is there first. Write:If Dir(filePath) <> "" Then. This checks if the directory returns a filename; if it does, the file exists. - Execute the Kill Command: Inside the
Ifblock, place the deletion command:Kill filePath. - Close the Logic Block: End the conditional statement by typing
End If. - Add a Confirmation Message (Optional): To know the code worked, add
MsgBox "File deleted successfully!"after theEnd Ifline. - Run the Macro: Click anywhere inside the subroutine and press
F5or click the green "Run" arrow in the toolbar to execute the deletion.
Common Mistakes
One of the most frequent errors is failing to check if the file exists before attempting to delete it. The Kill statement is not "silent"; if the path is incorrect or the file has been moved, VBA will throw a "File not found" error (Error 53). Always wrap your deletion logic in a check using Dir() or use an On Error Resume Next statement, though the latter is generally discouraged as it can hide other critical bugs.
Another common mistake is forgetting the file extension. VBA cannot delete a file if you only provide the name (e.g., "Report") without the extension (e.g., ".pdf"). The path must be absolute and exact. Additionally, users often try to delete files that are currently open. If the file is open in Excel or another program, Windows places a lock on it, and VBA will return a "Permission denied" error (Error 70).
Incorrect path formatting is also a recurring issue. In VBA strings, the backslash is the standard separator for Windows paths. If you are building a path dynamically using variables, ensure there is exactly one backslash between the folder path and the filename. A common error is having a missing backslash (e.g., "C:\FolderFile.txt" instead of "C:\Folder\File.txt").
Tips
To make your code more flexible, use a file dialog box instead of a hard-coded path. This allows the user to browse for the file they want to delete. You can achieve this using Application.GetOpenFilename in Excel, which returns the path of the selected file as a string.
If you need to delete multiple files with the same extension (for example, all .tmp files in a folder), you can use wildcards. The Kill command supports the asterisk (*) symbol. For example, Kill "C:\Temp\*.tmp" will delete every file ending in .tmp in that specific directory. Use this with extreme caution, as there is no "Undo" for this action.
For better error handling, implement a Try-Catch style block using On Error GoTo ErrorHandler. This allows you to redirect the code to a specific section if a deletion fails, where you can provide a user-friendly message explaining why the file couldn't be deleted (e.g., "The file is currently open in another program").
Troubleshooting
If the code does not work, first check the "Permission denied" error. This usually means the file is open. Close all instances of the file and any programs that might be indexing it (like a cloud sync tool or an antivirus scanner) and try again. If you are attempting to delete a file in a protected system directory (like C:\Windows), you must run the Office application as an Administrator.
If you receive a "Path not found" error, verify the directory string. Copy the path directly from the Windows File Explorer address bar and paste it into your code. Ensure there are no leading or trailing spaces in your string variables. If you are using a network drive, ensure the drive is mapped correctly and that you have "Modify" or "Full Control" permissions on the network share.
If the Dir function is returning an empty string even though you can see the file, check if the file is hidden. The standard Dir(filePath) call does not see hidden files. To include hidden files in your check, use Dir(filePath, vbHidden).
Frequently Asked Questions
Does the Kill command send files to the Recycle Bin?
No, the Kill statement deletes files permanently. They bypass the Recycle Bin and cannot be restored through standard Windows recovery tools. Always ensure you have a backup before running deletion scripts.
Can I use VBA to delete a folder instead of a file?
The Kill command only works for files. To delete an entire folder, you should use the RmDir statement. However, RmDir only works if the folder is completely empty. If the folder contains files, you must use Kill to delete the files inside first, or use the FileSystemObject (FSO) DeleteFolder method.
What is the difference between Kill and FileSystemObject.DeleteFile?
Kill is a native VBA command and is faster for simple tasks. FileSystemObject (part of the Scripting library) is more powerful, offering better error handling and the ability to force the deletion of read-only files using a True/False parameter.
How do I delete a file that is marked as Read-Only?
The Kill command will fail on read-only files. You must first change the file attribute using the SetAttr command. Use SetAttr filePath, vbNormal to remove the read-only attribute, then call the Kill command.
Can VBA delete files on a cloud drive like OneDrive?
Yes, as long as the OneDrive folder is synced locally to your PC. You must provide the local path (e.g., "C:\Users\Name\OneDrive\file.txt") rather than the URL (https://...). If the file is "online-only", the command may fail depending on the sync status.