vba delete files header

VBA Delete File – Deleting files using VBA

1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 5.00 out of 5)
Loading...

To delete a file using VBA you need to use the VBA Kill Function. The problem with the VBA Kill function however is that it will not check whether the file exists in the first place, and instead will throw and error.

VBA Deleting multiple files using Wildcards (*)

In case you have many files to delete in a single directory that match a certain sequence of characters in the name you can use Wildcards (*).

A Wildcard (*) replaces any number of characters (more than one) in the filename. An example below:

VBA Deleting files matching a Regular Expression

In some cases there are more complex rules defining the files we should delete. In such case we can create a new function that uses VBA Regular Expressions:

Having this functions we can delete files using patterns (be sure to read my VBA Regular Expression tutorial if you are new to Regex).

Let us use this example below.
vba delete file
I would like to delete files “1.txt” and “2.txt” while maintaining remaining files. Hence I can use the Regex pattern [0-9] which means any single numeric digit. Execution would look hence like this:

VBA Delete files recursively

In some cases you might not know if which directory the file you want to delete is and you have only a root directory. Traversing these folder manually is cumbersome. However with the help of my TraversePath procedure which I created in the postVBA Dir Function – How to traverse directories we can create our own RecursiveKill function:

Now using the same example from above let us assume we have the file 1.txt copied multiple times across our directory. We can easily delete all copies like this:

Related Posts