创建特定文件夹

时间:2018-02-20 08:54:35

标签: vba excel-vba excel

我正在使用这两个函数在启动时创建项目文件夹。在开始时,我只创建了一个名为ProjectName的文件夹,但现在在同一级别上有其他文件夹,其中ProjectName名为ProjectName_InputsProjectName_FilesProjectName_Outputs。我想用下面的代码创建它们。

我想知道如何将其改编为我的代码。我的意思是,是否可以使用数组或循环等? path = [/ProjectName, ProjectName_Inputs, ProjectName_Files, ProjectName_Outputs]我不知道是否可能?

或者你能建议一种更合乎逻辑的方式来创建它们吗?

Sub CreateFolders()

Dim fso As New FileSystemObject

If Functions.FolderExists(path) Then
    Exit Sub
Else
    On Error GoTo FolderNotBuilt
    fso.CreateFolder path ' could there be any error with this, like if the path is really screwed up?
    Exit Sub
End If

FolderNotBuilt:
    MsgBox "A folder could not be created for the following path: " & path & ". Check the path name and try again."
    FolderCreate = False
    Exit Sub

End Sub

这是控制是否在

之前创建目录的函数
Function FolderExists(ByVal path As String) As Boolean

FolderExists = False
Dim fso As New FileSystemObject

If fso.FolderExists(path) Then FolderExists = True

End Function

1 个答案:

答案 0 :(得分:1)

已编辑修改拼写错误(End With缺失)并将Resume更改为Resume Next并跳过可能搞砸的路径

我会像以下那样

Sub CreateFolders()
    Dim path As Variant

    With CreateObject("Scripting.FileSystemObject") 'create and reference a FileSystemObject object
        For Each path In Array("path1*\", "path2", "path3")
            If Not .FolderExists(path) Then 'loop through paths in array
                On Error GoTo FolderNotBuilt
                .CreateFolder path ' could there be any error with this, like if the path is really screwed up?
            End If
        Next
    End With
Exit Sub

FolderNotBuilt:
    MsgBox "A folder could not be created for the following path: " & vbCrLf & vbCrLf & path & vbCrLf & "Check the path name and try again."
    Resume Next
End Sub