vba 不使用 FileSystemObject 删除目录及其内容(文件、子目录)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/25401789/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove directory and it's contents (files, subdirectories) without using FileSystemObject
提问by Eldar Agalarov
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.FolderExists(dir) Then Call fso.DeleteFolder(dir, True)
    Call fso.CreateFolder(dir)
End Sub
With VBA statements: Kill, MkDir, etc. Most "difficult" part of this - remove non-empty directory. With FSO it can be done easily, but how it can be done without FSO?
使用 VBA 语句:Kill、MkDir 等。这其中最“困难”的部分 - 删除非空目录。使用 FSO 可以轻松完成,但没有 FSO 如何完成?
回答by PaulFrancis
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.
这段代码使用 RmDir 删除文件夹。AFAIK,RmDir 不能删除文件夹,除非它是空的,所以我们先清除文件夹中的内容,然后删除目录。
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.
希望这可以帮助。
回答by ashleedawg
The OP said they want to rewrite their code "without FSO" but it doesn't make sense.
OP 说他们想在“没有FSO”的情况下重写他们的代码,但这没有意义。
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 permanentlyremoves the folder andit's contents.
根据要求,这将永久删除文件夹及其内容。
More Information:
更多信息:
- Microsoft Docs : DeleteFolder Method
- Ron de Bruin : Delete files and folders

