Excel VBA: Check If File Exists and Delete
To check if a file exists and delete it in Excel VBA, use the Dir function to test for its existence, then the Kill statement to remove it. This article explains the exact code, common pitfalls, and safer alternatives.
Why Check Before Deleting?
Deleting a file without checking first can cause a runtime error if the file is missing. In VBA, the Kill statement throws error 53 (File not found) when the specified file doesn’t exist. Wrapping the deletion in an existence check prevents this error and makes your macro more robust.
The Basic Code
Here is the fundamental pattern you’ll use:
Dim filePath As String
filePath = "C:\Users\YourName\Documents\example.txt"
If Dir(filePath) <> "" Then
Kill filePath
MsgBox "File deleted."
Else
MsgBox "File not found."
End If
The Dir function returns the filename if the file exists, or an empty string if it doesn’t. So the condition Dir(filePath) <> "" is true only when the file exists.
Using FileSystemObject (FSO)
Another approach is to use the FileSystemObject from the Microsoft Scripting Runtime library. This provides a more object-oriented way and can be easier to read for complex file operations.
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FileExists(filePath) Then
fso.DeleteFile filePath
MsgBox "File deleted."
Else
MsgBox "File not found."
End If
To use FSO, you can either create it on the fly with CreateObject (as above) or set a reference to “Microsoft Scripting Runtime” in the VBA editor (Tools → References). The CreateObject method works without the reference, but you lose IntelliSense.
Handling Errors Gracefully
Even with a check, errors can still occur—for example, if the file is open in another program or you lack permissions. A robust approach is to combine the check with an error handler:
Sub DeleteFileSafe(filePath As String)
On Error Resume Next
Kill filePath
If Err.Number = 0 Then
MsgBox "File deleted."
ElseIf Err.Number = 53 Then
MsgBox "File not found."
Else
MsgBox "Error " & Err.Number & ": " & Err.Description
End If
On Error GoTo 0
End Sub
This method doesn’t need a separate existence check because the error handler catches the “file not foundâ€� case. It also catches permission errors and other issues.
Deleting Files with Wildcards
Sometimes you may want to delete all files matching a pattern (e.g., all .tmp files in a folder). The Dir function supports wildcards, and you can loop through matches:
Dim folderPath As String
Dim fileName As String
folderPath = "C:\Temp\"
fileName = Dir(folderPath & "*.tmp")
Do While fileName <> ""
Kill folderPath & fileName
fileName = Dir ' get next file
Loop
Be careful: the first call to Dir uses the full path, but subsequent calls must use Dir with no arguments to get the next match.
Common Mistakes and Pitfalls
- Forgetting the full path: If you use a relative path, VBA searches the current working directory, which may not be where you expect. Always use absolute paths or build them from
ThisWorkbook.Path. - Not handling the “file in use� error: If the file is open in Excel or another program,
Killwill fail with a permission error. The error handler above will catch this. - Using
Dirwith a folder:Diralso works on folders, so if you pass a folder path, it returns the folder name. To check specifically for a file, you can add thevbDirectoryattribute check, but for most cases this isn’t needed. - Deleting read-only files:
Killcan delete read-only files, but you may get an error if the file is write-protected by the operating system. In that case, you need to clear the read-only attribute first usingSetAttr.
Deleting Files from a List or Array
Often you’ll have a list of file paths in a worksheet or an array. You can loop through them:
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
Dim i As Long
For i = 1 To 10 ' assuming 10 files in column A
Dim fPath As String
fPath = ws.Cells(i, 1).Value
If fPath <> "" Then
If Dir(fPath) <> "" Then Kill fPath
End If
Next i
This pattern is useful for cleaning up temporary files or processing a batch of files.
Frequently Asked Questions
Can I delete a file without checking if it exists?
Technically yes, but you’ll get a runtime error if it doesn’t exist. Use On Error Resume Next to ignore the error, but then you won’t know if the deletion succeeded. Better to check or handle the error properly.
How do I delete a file that is open in another program?
You can’t delete a file that is currently open and locked by another process. You’ll need to close the program or handle the error gracefully. In some cases, you can use Kill after clearing the read-only attribute, but the lock remains.
What is the difference between Kill and FileSystemObject.DeleteFile?
Both delete files. Kill is a native VBA statement that works with strings. DeleteFile is a method of the FileSystemObject, which offers more features like checking existence and handling wildcards. FSO also allows you to delete files with a path that contains special characters more easily.
Can I delete multiple files at once?
Yes, you can use wildcards with Kill (e.g., Kill "C:\Temp\*.tmp") to delete all matching files. However, this will fail if no files match. To avoid that, check with Dir first or use an error handler.
How do I delete a folder and all its contents?
Use RmDir for empty folders, or the FileSystemObject’s DeleteFolder method to remove a folder and everything inside it. Be extremely careful—this is irreversible.
Is there a way to send a file to the Recycle Bin instead of permanent deletion?
VBA’s Kill permanently deletes the file. To send to the Recycle Bin, you need to use the Windows API (e.g., SHFileOperation) or a third-party library. This is more complex and beyond the scope of a simple check-and-delete.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.