how to delete files from a directory using VBA

  • Thread starter Luká¹ Cyrankowski
  • Start date
L

Luká¹ Cyrankowski

hallo, my friends,

does anybody know how to delete all files in a concrete directory on a disc
from VBA code?

p.e. in C:\reports - there are already files "....TXT" and at the start of
the VBA I need to have this directory empty.

thanx a lot, Lukas.
 
H

Helmut Weber

Hi Lukas,

like this and in some other ways:

Sub Macro11()
Dim aFile As String
aFile = Dir("c:\temp\*.*", vbNormal)
While aFile <> ""
Kill "c:\temp\" & aFile
aFile = Dir
Wend
End Sub

And have a look at the help for "Dir Function".

--
Greetings from Bavaria, Germany

Helmut Weber, MVP WordVBA

Win XP, Office 2003
"red.sys" & Chr$(64) & "t-online.de"
 
K

Karl E. Peterson

Helmut said:
Dim aFile As String
aFile = Dir("c:\temp\*.*", vbNormal)
While aFile <> ""
Kill "c:\temp\" & aFile
aFile = Dir
Wend

Fwiw, a lot of folks have been burned with that general strategy. The "safe" way to
process all files returned by a Dir() loop is to insert them into an array first, and
then iterate the array. If the folder content changes (by deletion, addition,
whatever) during a Dir() loop, the results can become rather unpredictable.
 
K

Karl E. Peterson

Karl said:
Fwiw, a lot of folks have been burned with that general strategy.
The "safe" way to process all files returned by a Dir() loop is to
insert them into an array first, and then iterate the array. If the
folder content changes (by deletion, addition, whatever) during a
Dir() loop, the results can become rather unpredictable.

Overkill for this specific task, but for a very generalized (and robust) approach,
see: http://vb.mvps.org/samples/DirDrill
 

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

Top