Deleting directories and subdirectories in VBA

GKite

Registered User.
Local time
Today, 22:07
Joined
Mar 22, 2002
Messages
29
I found an old subject that shows how to delete files and folders. However, it only shows how to delete folders if you know the name. How can I delete all folders (in a certain location) and their subfolders, without knowing the names? Basically I need to automate clearing out a certain folder, regardless of the contents.
 
use this function:

Public Sub KillDirs(stDirName As String)

'purpose: deletes all files and directories in the the directory
'passed to it

Dim TheDir2Kill As String 'holds Dir string
Dim TheDir As String

TheDir2Kill = Dir(stDirName & "\", vbDirectory)
On Error Resume Next
'iterate through the subdirectories
Do While TheDir2Kill <> ""
If TheDir2Kill <> "." And TheDir2Kill <> ".." Then
TheDir = stDirName & "\" & TheDir2Kill
'kill all files in the directory
Kill TheDir & "\*.*"
'kill the directory itself
RmDir TheDir & "\"
End If
TheDir2Kill = Dir
Loop
End Sub


Use it like:

KillDirs "C:\tmpdir"

This will kill all dirs and files in the stated path.

HTH

Ian
 
This didn't work! It deleted nothing. I used your code exactly and nothing happened. What could I be doing wrong? How does this work without knowing the subdirectory names?
 
It does work because I have used it in a VB program where I have directories set up for days of the week and it does delete all files in each directory Monday, Tuesday, Wednesday, Thursday, Friday. In fact, because I hadn't used it for a while I tested it again before posting it.

In answer to your question, the reason it probably isn't working in your example is because you have further subdirectories in your subdirectories, therefore it won't delete those properly.

In answer to your question, it doesn't need to know the sub-directory name because that it returned by the Dir function.

let me ask a question that will make all our lives easier:

Are the directories and subdirectories static or do you create them dynamically?

Ian
 
Is there any way to use the full name with RmDir?

I have tried and successfully been able to use the function listed above. Unfortunately I have a production system that uses very long folder names. Is there any way to adjust this function so that you can delete with actual folder names instead of the ~1 or ~2, etc.

I hope I'm explaining the problem sufficiently. I believe that RmDir is a older dos function and needs to truncate the folder name to 8.3 - if I'm wrong please let me know.
 

Users who are viewing this thread

Back
Top Bottom