Remove directory and it's contents (files, subdirectories) without using FileSystemObject

前端 未结 3 2003
醉梦人生
醉梦人生 2020-12-11 17:44

I want to know if it\'s possible to rewrite this piece of code:

Private Sub PrepareDir(ByVal dir As String)
    Dim fso As New FileSystemObject
    If fso.Fo         


        
相关标签:
3条回答
  • 2020-12-11 18:19

    No need to delete files for Deleting folders. Take the path and search for the sub folders in a loop and that sub folder can be deleted. below is the example :copy both procedures and paste on module

    Public Function Delete_Folder(ByVal FldrName As String) Dim fso, FSfolder As Object

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set FSfolder = fso.GetFolder(Application.DefaultFilePath)' This is My Documents folder path
    

    'You can replace with your original folder path

    For Each Folder In FSfolder.SubFolders
        'Debug.Print Folder.Name
        If Folder.Name = FldrName Then
            Folder.Delete
            Exit For
        End If
    Next
    

    End Function

    Sub test() Delete_Folder "Sub_Folder_Name" End Sub

    0 讨论(0)
  • 2020-12-11 18:23

    This piece of ccode uses RmDir to remove the Folder. AFAIK, RmDir cannot delete the folder unless it is empty, so we first clear the content in the folder then remove the directory.

    Private Sub PrepareDirModified(dirStr As String)
    On Error Resume Next
        If Right(dirStr, 1) <> "\" Then dirStr = dirStr & "\"
        Kill dirStr & "*.*" 
        RmDir dirStr
        MkDir dirStr
    On Error GoTo 0
    End Sub
    

    Hope this helps.

    0 讨论(0)
  • 2020-12-11 18:24

    The OP said they want to rewrite their code "without FSO" but it doesn't make sense.

    If the goal is to reduce the amount of code, simply make it a one-liner:

    CreateObject("Scripting.FileSystemObject").DeleteFolder "x:\myFolder"
    

    As requested, this permanently removes the folder and it's contents.


    More Information:

    • Microsoft Docs : DeleteFolder Method
    • Ron de Bruin : Delete files and folders
    0 讨论(0)
提交回复
热议问题