我如何使用VBA在Excel工作表中创建例如5个文件夹?

时间:2018-06-22 12:27:38

标签: excel vba excel-vba

我正在使用以下vba代码使用excel工作表的数据创建文件夹结构:

Option Explicit

Declare Function MakePath& Lib "imagehlp.dll" Alias _
   "MakeSureDirectoryPathExists" (ByVal sPath$)

Sub CreatePaths()
Dim i&
With Tabelle1
For i = 1 To .Cells(.Rows.Count, "E").End(xlUp).Row
MakePath .Cells(i, "E").Text
Next
End With
End Sub

“ C:\ Users \ xxxxx \ Desktop \ test \ H01 \ U01 \ UU01”

每行都将创建为我选择的文件夹中的文件夹结构,直到这里行完成我需要的操作为止。 E列添加A-D列,并用反斜杠分隔。现在,我需要在“ E”列的每个文件夹中添加例如4个文件夹(A,B,C,D),我试图添加它,但它不起作用。我必须在vba代码中添加些什么,以便创建文件夹?

随时提问。 myExcelsheet

2 个答案:

答案 0 :(得分:2)

怎么样呢?

Option Explicit

Declare Function MakePath& Lib "imagehlp.dll" Alias _
    "MakeSureDirectoryPathExists" (ByVal sPath$)

Sub CreatePaths()

Dim i&, subfolders As Variant, subfolder As Variant
subfolders = Split("A,B,C,D", ",")

With Tabelle1
    For i = 1 To .Cells(.Rows.Count, "E").End(xlUp).Row
        For Each subfolder In subfolders
            MakePath .Cells(i, "E").Text & "\" & subfolder
        Next
    Next
End With

End Sub

答案 1 :(得分:1)

请尝试执行此操作,因为您在A列中有一个根文件夹。我们将其称为ParentDirectory,然后遍历内部文件夹,在B,C,D列中,我们将创建单独的文件夹名称“ A,B” ,C,D”。

Option Explicit

Declare Function MakePath& Lib "imagehlp.dll" Alias _
   "MakeSureDirectoryPathExists" (ByVal sPath$)

Sub CreatePaths()

Dim i As Integer, x As Integer
Dim currentDirectory As String, parentDirectory As String
With Tabelle1
For i = 1 To .Cells(.Rows.Count, "E").End(xlUp).Row
    parentDirectory = .Cells(i, 1) & "\"
    For x = 2 To 4
        currentDirectory = parentDirectory & .Cells(i, x).Text & "\"
        MakePath currentDirectory
        MakePath currentDirectory & "A\"
        MakePath currentDirectory & "B\"
        MakePath currentDirectory & "C\"
        MakePath currentDirectory & "D\"
        parentDirectory = currentDirectory
    Next x
Next
End With
End Sub