Deleting a file in VBA

520,117

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
Share:
520,117
Gabriel Santos
Author by

Gabriel Santos

Updated on July 19, 2022

Comments

  • Gabriel Santos
    Gabriel Santos almost 2 years

    Using VBA, how can I:

    1. test whether a file exists, and if so,
    2. delete it?
  • Onorio Catenacci
    Onorio Catenacci over 15 years
    You 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
    JimmyPena over 12 years
    I 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
    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
    Renaud Bompuis over 9 years
    The reason that Len() (and LenB(), 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. Use vbNullString instead as it is a constant and does not uses more memory.
  • pghcpa
    pghcpa about 9 years
    Using this syntax without declaring a file scripting object, must add reference for Microsoft Scripting Runtime, else: Dim fs As New Scripting.FileSystemObject
  • ekkis
    ekkis almost 9 years
    you also need to reference the scripting library. see here: stackoverflow.com/questions/3233203/…
  • mauek unak
    mauek unak over 8 years
    I use FileSystemObject method too, as Kill is unable to delete files/folders with diacritis
  • BenKoshy
    BenKoshy almost 8 years
    thank 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
    Onorio Catenacci almost 8 years
    You can't have two files with the same name in a directory.
  • johny why
    johny why over 7 years
    but 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
    johny why over 7 years
    This is a great alternative, if asynch is what you want.
  • johny why
    johny why over 7 years
    Since 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
    jony over 7 years
    No, 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
    elektrykalAJ about 5 years
    The 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 part SetAttr FileToDelete, vbNormaleloquently takes care of this for you.
  • Gregg Burns
    Gregg Burns over 4 years
    This 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)