我想使用以下代码创建一个目录和一个子目录:
Public fso As Scripting.FileSystemObject
Set fso = New Scripting.FileSystemObject
fso.CreateFolder ("C:\Users\<my_username>\DataEntry\logs")
我正在尝试创建嵌套目录。在这种情况下,DataEntry
目录将不存在,所以本质上我想创建 2 个目录, DataEntry\logs
下C:\Users\<username>
如果我输入命令提示符,我可以使用 mkdir
创建该目录没有任何问题。但是,我根本无法让 VBA 创建该文件夹,我得到:
Run-time error '76':
Path not found
我使用的是 Excel VBA 2007/2010
最佳答案
tigeravatar 的循环答案可能有效,但有点难以阅读。 FileSystemObject 具有可用的路径操作函数,而不是您自己对字符串处理进行微观管理,并且递归比循环更容易阅读。
这是我使用的函数:
Function CreateFolderRecursive(path As String) As Boolean
Dim FSO As New FileSystemObject
'If the path exists as a file, the function fails.
If FSO.FileExists(path) Then
CreateFolderRecursive = False
Exit Function
End If
'If the path already exists as a folder, don't do anything and return success.
If FSO.FolderExists(path) Then
CreateFolderRecursive = True
Exit Function
End If
'recursively create the parent folder, then if successful create the top folder.
If CreateFolderRecursive(FSO.GetParentFolderName(path)) Then
If FSO.CreateFolder(path) Is Nothing Then
CreateFolderRecursive = False
Else
CreateFolderRecursive = True
End If
Else
CreateFolderRecursive = False
End If
End Function
关于vba - FileSystemObject.CreateFolder 创建目录和子目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31033820/