本文介绍了FileSystemObject.CreateFolder创建目录和子目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to create a directory and a subdirectory with the following code:

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

我正在尝试创建嵌套目录.在这种情况下,DataEntry目录将不存在,因此本质上我想创建2个目录,在C:\Users\<username>

I am trying to create nested directories. In this case, the DataEntry directory would not exist, so essentially I would like to create 2 directories, DataEntry\logs under C:\Users\<username>

如果输入命令提示符,则可以使用mkdir创建该目录,而不会出现任何问题.但是,我根本无法让VBA创建该文件夹,并且得到:

If I enter command prompt, I can create that directory with mkdir without any issues. However, I simply cannot get VBA to create that folder and I get:

Run-time error '76':

Path not found

我正在使用Excel VBA 2007/2010

I am using Excel VBA 2007/2010

推荐答案

需要一次创建一个文件夹.您可以使用以下代码来做到这一点:

Need to create each folder one at a time. You can use code like this to do so:

Sub tgr()

    Dim strFolderPath As String
    Dim strBuildPath As String
    Dim varFolder As Variant

    strFolderPath = "C:\Users\<my_username>\DataEntry\logs"

    If Right(strFolderPath, 1) = "\" Then strFolderPath = Left(strFolderPath, Len(strFolderPath) - 1)
    For Each varFolder In Split(strFolderPath, "\")
        If Len(strBuildPath) = 0 Then
            strBuildPath = varFolder & "\"
        Else
            strBuildPath = strBuildPath & varFolder & "\"
        End If
        If Len(Dir(strBuildPath, vbDirectory)) = 0 Then MkDir strBuildPath
    Next varFolder

    'The full folder path has been created regardless of nested subdirectories
    'Continue with your code here

End Sub

这篇关于FileSystemObject.CreateFolder创建目录和子目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 14:54