Deleting a file in VBA
Solution 1
1.) Check here. Basically do this:
Function FileExists(ByVal FileToTest As String) As Boolean
FileExists = (Dir(FileToTest) <> "")
End Function
I'll leave it to you to figure out the various error handling needed but these are among the error handling things I'd be considering:
- Check for an empty string being passed.
- Check for a string containing characters illegal in a file name/path
2.) How To Delete a File. Look at this. Basically use the Kill command but you need to allow for the possibility of a file being read-only. Here's a function for you:
Sub DeleteFile(ByVal FileToDelete As String)
If FileExists(FileToDelete) Then 'See above
' First remove readonly attribute, if set
SetAttr FileToDelete, vbNormal
' Then delete the file
Kill FileToDelete
End If
End Sub
Again, I'll leave the error handling to you and again these are the things I'd consider:
Should this behave differently for a directory vs. a file? Should a user have to explicitly have to indicate they want to delete a directory?
Do you want the code to automatically reset the read-only attribute or should the user be given some sort of indication that the read-only attribute is set?
EDIT: Marking this answer as community wiki so anyone can modify it if need be.
Solution 2
An alternative way to code Brettski's answer, with which I otherwise agree entirely, might be
With New FileSystemObject
If .FileExists(yourFilePath) Then
.DeleteFile yourFilepath
End If
End With
Same effect but fewer (well, none at all) variable declarations.
The FileSystemObject is a really useful tool and well worth getting friendly with. Apart from anything else, for text file writing it can actually sometimes be faster than the legacy alternative, which may surprise a few people. (In my experience at least, YMMV).
Solution 3
I'll probably get flamed for this, but what is the point of testing for existence if you are just going to delete it? One of my major pet peeves is an app throwing an error dialog with something like "Could not delete file, it does not exist!"
On Error Resume Next
aFile = "c:\file_to_delete.txt"
Kill aFile
On Error Goto 0
return Len(Dir$(aFile)) > 0 ' Make sure it actually got deleted.
If the file doesn't exist in the first place, mission accomplished!
Solution 4
The following can be used to test for the existence of a file, and then to delete it.
Dim aFile As String
aFile = "c:\file_to_delete.txt"
If Len(Dir$(aFile)) > 0 Then
Kill aFile
End If
Solution 5
In VB its normally Dir
to find the directory of the file. If it's not blank then it exists and then use Kill
to get rid of the file.
test = Dir(Filename)
If Not test = "" Then
Kill (Filename)
End If
Gabriel Santos
Updated on July 19, 2022Comments
-
Gabriel Santos almost 2 years
Using VBA, how can I:
- test whether a file exists, and if so,
- delete it?
-
Onorio Catenacci over 15 yearsYou raise a good point but, like most things, I think it would depend on context and sometimes simply having a "File Exists" function is handy apart from deletion.
-
JimmyPena over 12 yearsI know this question and response are old, just thought I'd add that using Len() to test strings (and functions that return strings) seems to be faster than literal string comparisons in VBA.
-
Joël over 10 years+1: maybe the user of the application wants to be asked before removing a file: for instance, using
ActiveWorkbook.SaveCopyAs
is not able to overwrite, so you first have to remove existing file with same filename. -
Renaud Bompuis over 9 yearsThe reason that
Len()
(andLenB()
, which is even faster) are faster than string comparison is that in memory, VB strings are preceded by their length. Len/LenB just pull the length from that memory location, they don't have to iterate through the string to know its length. On the other hand, using string comparison has much more work to do. Additionally, avoid using""
in VB as it always allocates a new string. UsevbNullString
instead as it is a constant and does not uses more memory. -
pghcpa about 9 yearsUsing this syntax without declaring a file scripting object, must add reference for Microsoft Scripting Runtime, else: Dim fs As New Scripting.FileSystemObject
-
ekkis almost 9 yearsyou also need to reference the scripting library. see here: stackoverflow.com/questions/3233203/…
-
mauek unak over 8 yearsI use FileSystemObject method too, as Kill is unable to delete files/folders with diacritis
-
BenKoshy almost 8 yearsthank you - what if there are two files of the same name which exist will the DeleteFile sub kill both of them or only one? any advice much appreciated.
-
Onorio Catenacci almost 8 yearsYou can't have two files with the same name in a directory.
-
johny why over 7 yearsbut you should never use
On Error Resume Next
, or so i've been told :D Of course, that's ridiculous advice, and your answer is correct. -
johny why over 7 yearsThis is a great alternative, if asynch is what you want.
-
johny why over 7 yearsSince there's no variable to set to Nothing, is there a risk the FileSystemObject will remain in memory, causing a leak or other issue?
-
jony over 7 yearsNo, it will be discarded after the "End With". Since it is not assigned to a variable the effect is similar to the object having been assigned to a variable that has been set to "Nothing".
-
elektrykalAJ about 5 yearsThe
Len(dir(...))
part isn't SOLELY to check for existence. It is also checking if the file is HIDDEN because a hidden file will return an empty string even if it exists (and you won't be able to delete it):Dir(hiddenFile) = ""
. Hence, the partSetAttr FileToDelete, vbNormal
eloquently takes care of this for you. -
Gregg Burns over 4 yearsThis is method I use.. Someone who implements this wants to use error checking and DisplayAlerts = false. (The file won't delete if it's in use, so must have error trap)