How do I delete a folder including files in a code?
Printable View
How do I delete a folder including files in a code?
DeleteFolder Method
Description
Deletes a specified folder and its contents.
Syntax
object.DeleteFolder folderspec[, force]
The DeleteFolder method syntax has these parts:
Part Description
object Required. Always the name of a FileSystemObject.
folderspec Required. The name of the folder to delete. The folderspec can contain wildcard characters in the last path component.
force Optional. Boolean value that is True if folders with the read-only attribute set are to be deleted; False (default) if they are not.
Remarks
The DeleteFolder method does not distinguish between folders that have contents and those that do not. The specified folder is deleted regardless of whether or not it has contents.
An error occurs if no matching folders are found. The DeleteFolder method stops on the first error it encounters. No attempt is made to roll back or undo any changes that were made before an error occurred.
Just an example:
VB Code:
Private Sub Command1_Click() Set fs = CreateObject("Scripting.FileSystemObject") fs.Deletefolder "c:\MyFolder", True End Sub
Why doesen't this code work with NT? It works with Win98?
VB Code:
Dim fso As New FileSystemObject Dim fldr As Folder Private Sub Command1_Click() Set fldr = fso.GetFolder("C:\Winnt\Test") fldr.Delete True End Sub
Try thisVB Code:
Private Sub DeleteFolder(FolderPath) 'Purpose: This function will delete all the folder(s) and its 'contents under the root folder. All you need to do is to pass in 'the Path as a Parameter 'Usage: Call DeleteFolder("d:\temp\") 'From: [url]www.vbcode.com[/url] by Dan Liu Dim MyFile, MyPath, MyName Dim Fs As Scripting.FileSystemObject Set Fs = CreateObject("Scripting.FileSystemObject") ' Display the names that represent directories. MyPath = FolderPath ' Set the path. MyName = Dir(MyPath, vbDirectory) ' Retrieve the first entry. Do While MyName <> "" ' Start the loop. ' Ignore the current directory and the encompassing directory. If MyName <> "." And MyName <> ".." Then ' Use bitwise comparison to make sure MyName is a directory. If (GetAttr(MyPath & MyName) And vbDirectory) = vbDirectory Then MsgBox MyPath & MyName Fs.DeleteFolder (MyPath & MyName) End If ' it represents a directory. End If MyName = Dir ' Get next entry. Loop End Sub
Hack,
Does this code work with NT? What's the differens between this code and the code i suggested?