Check to see if files exists and delete it.

  • Thread starter Thread starter Steven M. Britton
  • Start date Start date
S

Steven M. Britton

How can I check to see if there are files in a directory,
and if the directory contains files delete all of them?

-Steve
 
You can use the Shell command to do this from a Dos window. You can also use
the VBA Dir, Kill, ChDir, RmDir, and SetAttr commands.

To simply delete all files in a folder use

Kill <path>\*.*

However, this won't remove subdirectories, open files, or files set as
Hidden, System, or Read Only. To do that, you'll have to use the other
commands. To remove subdirectories, you have to run through the directory
tree recursively. I tend to find it easiest just to put Deltree (from Dos 6,
Win9x) in the path or somewhere that I know where it is at and Shell to a
command prompt calling Deltree. You would call Command.com or Cmd.exe with
the /C switch.
 
Wayne:

I only want to do this in VBA, I use the kill command
however if there are no files to delete it tells me "File
not found" and exits the sub.

I guess I should further explain my problem. I have
Access exporting .txt files via a TransferText and a
query, once I export he .txt files I use Name so that I
can rename them as .CSV files for other various uses. A
problem arises when I try to rename the file and it
already exist, because the user forgot to erase the
previous file.

Any Ideas?

-Steve
 
On Error resume next

'If the file doesn't exist...ignore the error
Kill "C:\somefile.txt"

On Error Goto err_Handler
'Resume error handling
 
As Wayne noted you can use the dir function:
if dir("c:\path\")>"" then kill "c:\path\*.*"
 
If Len(Dir("C:\path\filename.ext") > 0 Then
' File filename.ext exists in folder C:\path
Else
' File filename.ext does not exist in folder C;\path
End If
 
There are several ways around the error as you've seen mentioned here. The
error number is 53 if you want to trap it in an error handler or you could
just place an On Error Resume Next before the statement. Remember to
reinitiate your normal error handling after the statement if you do this.
You could also use Dir to see if at least one file meeting the criteria
exists first.
 
Back
Top