deleting file(s) by their file extension

  • Thread starter Thread starter jt46
  • Start date Start date
J

jt46

Does anyone knows how to write a simple code to delete a file or file
by their file extension? Thanks in advance.

Joh
 
Kill "C:\test1\*.txt"

These don't go to the recycle bin, so make sure you know what you want to
delete.
 
This function will delete all files with a given extension in a specified
folder; e.g. Clean("C:\TEMP","xml") will delete any .xml files in the
C:\TEMP folder. It returns the number of files deleted and also (if you need
to check the file names) prints the files deleted in the debugger.

Public Function Clean(FolderPath As String, Extension As String) As Integer

Dim FileName As String, CountFiles As Integer

CountFiles = 0
FileName = Dir(FolderPath & "\*." & Extension)
While FileName <> ""
debug.print FolderPath & "\" & FileName
Kill FolderPath & "\" & FileName
CountFiles = CountFiles + 1
FileName = Dir
Wend

Clean = CountFiles

End Function
 
Altering files in a Dir Loop can cause problems - or so sayeth the Knowledge
Base. I have never encountered any, but one never knows. In any event,
this can all be done in one line, so no use looping or using Dir.

Public Function Clean(FolderPath As String, Extension As String)
Kill FolderPath & "*." & Extension
End Sub

Error checking for valid arguments can be added.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top