vba - FileSystemObject.CreateFolder 创建目录和子目录

标签 vba excel

我想使用以下代码创建一个目录和一个子目录:

Public fso As Scripting.FileSystemObject
Set fso = New Scripting.FileSystemObject
fso.CreateFolder ("C:\Users\<my_username>\DataEntry\logs")

我正在尝试创建嵌套目录。在这种情况下,DataEntry目录将不存在,所以本质上我想创建 2 个目录, DataEntry\logsC:\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/

相关文章:

vb.net - VB.NET 中需要类似 Excel 的网格

excel - 在 VBA 中使用 Dir() 查找包含 ~ 的隐藏文件或系统文件

excel - 如何在 Excel 中将文本日期转换为日期格式,如 mm/dd/yyyy

vba - 通过草稿/发送/已发送过程跟踪电子邮件

excel - 如果在循环内定义变量,循环关闭后它是否仍然被定义?

excel - 用逗号替换句点会删除句点

ruby - 如何使用 Ruby 电子表格库格式化特定单元格?

excel - 如何使用 scala 解压 zip 文件?

vba - Excel 中未分配的热键

excel - VBA:如何为声明语句设置动态库路径?