TheSwamp
Code Red => VB(A) => Topic started by: ronjonp on December 02, 2008, 12:14:53 PM
-
All,
I found this code on the net to delete files and folders and modified it a bit to suit my needs. My question is, how can I turn it into a function that I can feed it a path and tell it how deep to delete the folders?
When I try to feed fldname a path i get an error "Expected literal constant"
Function deletefilesandfolders (foldername, deep)
const fldname = foldername
....
If UBound(Split (folder.path, "\")) > deep Then
....
End Function
deletefilesandfolders ("C:\Documents and Settings\%username%\Desktop\testdel2", 5)
const fldname = "D:\Garbage"
set fso = createobject("scripting.filesystemobject")
set fldr = fso.getfolder(fldname)
recurse fldr
sub recurse(byref fldr)
dim subfolders,files,folder,file
set subfolders = fldr.subfolders
set files = fldr.files
for each file in files
on error resume next
file.Delete
next
for each folder in subfolders
recurse folder
If UBound(Split (folder.path, "\")) > 2 Then
folder.Delete
End If
next
set subfolders = nothing
set files = nothing
end Sub
-
was is fldname a constant?
Try making it a variable:
...
dim fldname as string
fldname = foldername
...
-
That gives me a syntax error...I think the recursiveness is what is getting broken... :?
-
are trying to delete the folder given and all subfolders under that? could it be your feeding it 5 and there are 6 deep, or is it 0 based and you said 5 when you should have said 4
-
I'm trying to delete all subfolders except the subs directly under the path specified. It is zero based.
The routine works fine when run standalone...it's when I try to turn it into a function that can accept the path and nested number as a variable where it bonks out?
-
I got it working :-)
Function deletefilesandfolders (foldername, deep)
dim fso,fldr
set fso = createobject("scripting.filesystemobject")
set fldr = fso.getfolder(foldername)
deep = UBound(Split (foldername, "\")) + deep
recurse fldr, deep
Set fso = Nothing
Set fldr = Nothing
End Function
Sub recurse(byref fldr, deep)
dim subfolders,files,folder,file
set subfolders = fldr.subfolders
set files = fldr.files
for each file in files
on error resume next
file.Delete
next
for each folder in subfolders
recurse folder, deep
If UBound(Split (folder.path, "\")) > deep Then
folder.Delete
End If
next
set subfolders = nothing
set files = nothing
End Sub
deletefilesandfolders "d:\garbage", 0 '0==delete all subfolders . 1==leave subfolders 1 deep . 2==leave subfolders 2 deep...and so on...