I want to delete or destroy a folder which has one workbook in it.
How do i do it?
Printable View
I want to delete or destroy a folder which has one workbook in it.
How do i do it?
You have to remove the file first then use RmDir
VB Code:
Option Explicit Sub KillFolder() ' Folder Name: Const szFolderName As String = "FolderNameHere" Dim wkb As Workbook Dim szWkbNames As String Dim szOpenWkbNames As String Dim i As Long Dim szThisPath As String szThisPath = FixTrailingSeparator(ThisWorkbook.Path) Dim szProjectPath As String szProjectPath = szThisPath & szFolderName With Application.FileSearch .NewSearch .SearchSubFolders = False .LookIn = szProjectPath .FileType = msoFileTypeExcelWorkbooks .Execute If .FoundFiles.Count > 0 Then For i = 1 To .FoundFiles.Count Kill .FoundFiles(i) Next i End If End With RmDir szProjectPath End Sub Public Function FixTrailingSeparator(Path As String, _ Optional PathSeparator As String = "\") As String Select Case Right(Path, 1) Case PathSeparator FixTrailingSeparator = Path Case Else FixTrailingSeparator = Path & PathSeparator End Select End Function
Or with FSO as posted here
VB Code:
Sub RemoveDir_WithFiles() Dim objFSO As Object On Error GoTo DelErr '// CAUTION: Will delete entire Folder NO PROMPT Set objFSO = CreateObject("Scripting.FileSystemObject") objFSO.DeleteFolder "C:\Work\MyNewCrapFolder", True XitProperly: Set objFSO = Nothing Exit Sub DelErr: MsgBox "Error:=" & Err.Number & vbCr & Err.Description Resume XitProperly End Sub
A third option is to use an API to delete the file.
VB Code:
Private Declare Function DeleteFile Lib "kernel32.dll" Alias "DeleteFileA" (ByVal lpFileName As String) As Long