在VBA Excel中动态创建文件夹

时间:2019-05-15 18:56:33

标签: excel vba

我有几个文件需要分发到各自的文件夹中。如何使用Excel VBA宏检查是否存在具有动态名称的文件夹?

我将单个工作簿按其中的各个工作表拆分为多个工作簿。我相信,如果宏使用原始工作簿中每个工作表的名称来检查该文件夹是否存在,那将是最容易的。这样,它是动态的,并且我不必担心对它进行编码以搜索每个文件夹,因为数据源不断增长,并且需要其他工作表。我已经有了用于搜索文件夹的代码,我只需要了解如何编写它才能使其动态。

Dim Path As String
Dim Folder As String
Dim Answer As VbMsgBoxResult
Dim NewPath As String
NewPath = ActvieWorkbook.Sheets.Name
Path = "C:\Test" & NewPath
Folder = Dir(Path, vbDirectory)
For Each sheetz0r In ActiveWorkbook.Sheets
If Folder = vbNullString Then
    Answer = MsgBox("Path does not exist. Would you like to create it?", vbYesNo, "Create Path?")
    Select Case Answer
        Case vbYes
            VBA.FileSystem.MkDir (Path)
        Case Else
            Exit Sub
    End Select
End If
Next

在我编写的代码中,我只需要调整“ NewPath =“行,以便它将搜索工作表名称。

2 个答案:

答案 0 :(得分:1)

在循环体内移动Folder& NewPath分配,并用& sheetz0r.Name替换ActiveSheet.Sheets.Name-不确定Sheets应该是什么, Name集合类没有Dim sheet As Worksheet For Each sheet In ActiveWorkbook.Worksheets Dim Path As String Path = Dir("C:\Test" & sheet.Name, vbDirectory) If Path = vbNullString Then If MsgBox("Path does not exist. Would you like to create it?", vbYesNo, "Create Path?") = vbYes Then VBA.FileSystem.MkDir Path Else Exit For End If End If Next 成员。

我会稍微调整一下结构,删除多余的变量,并使声明更接近其用法。我认为您的意思是这样的吗?

FileSystemObject

也就是说,使用Scripting库中的With New Scripting.FileSystemObject Dim sheet As Worksheet For Each sheet In ActiveWorkbook.Worksheets Dim Path As String Path = "C:\Test\" & sheet.Name If Not .FolderExists(Path) Then If ConfirmCreateFolder(Path) Then .CreateFolder Path Else Exit For End If End If Next End With 来验证文件夹是否存在并创建一个新文件夹要容易得多/干净-我还将提要提示的部分提取到它自己的文件夹中功能:

Private Function ConfirmCreateFolder(ByVal Path As String) As Boolean
    Dim prompt As String
    prompt = "Folder '" & Path & "' does not exist. Would you like to create it?"
    ConfirmCreateFolder = (MsgBox(prompt, vbYesNo, "Create Folder?") = vbYes)            
End Function
imports: [
    BrowserModule,
    MatTableModule,
    MatSortModule
  ],

答案 1 :(得分:0)

尝试一下

{{1}}