在VB2010中创建子文件夹?

时间:2015-05-29 11:21:35

标签: vba

我处于需要为我的PC制作一堆文件夹的位置,所以我决定将其转换为编码任务。我设法让用户输入他们希望文件夹进入的位置,以及另一个文本框的每一行都是新文件夹的标题。

这就是问题所在。理想情况下,我希望在每个文件夹中放置多个文件夹,而无需再次运行程序。文本框看起来像这样,会导致folderA中的文件1,2和folderB中的文件3,4;

FolderA

档案1

文件2

FolderB中

档案3

档案4

这是我到目前为止所做的代码。

Dim Address As String = TextBox1.Text

    For i As Integer = 0 To RichTextBox1.Lines.Count - 1
            My.Computer.FileSystem.CreateDirectory(Address + (RichTextBox1.Lines(i)))
    Next

你知道我必须添加到我的代码中,以便它包含子文件夹吗? (我还没有学习很长时间,所以如果答案非常明显,我很抱歉。)

1 个答案:

答案 0 :(得分:0)

@punintentional

以下代码将完全符合您的要求。您必须确保具有Microsoft Office对象库的引用集。您可以通过转到工具>参考并找到相应的on来完成此操作。我使用Microsoft Office 12对象库设计了以下代码。如果您使用的是Office 2010,我认为该参考将适用于Microsoft Office 14对象库。

Option Explicit

Public Sub DirectorySelect()
    Dim diaFileDialog As FileDialog
    Dim blDirSelected As Boolean
    Dim strBaseDirectory As String
    Dim strA_Dir As String
    Dim StrB_Dir As String

'   set up a MS Office file dialog box to select a folder/directory
    Set diaFileDialog = Application.FileDialog(msoFileDialogFolderPicker)

    With diaFileDialog
        .AllowMultiSelect = False ' user may only select one base folder
        .Title = "Select the base director"  ' title of the dialog box

        blDirSelected = .Show  ' the .show method will return false if the user does not select a directory


        If blDirSelected = True Then   ' a directory was selected

            strBaseDirectory = .SelectedItems(1)  ' put the directory into a variable
            strBaseDirectory = strBaseDirectory & "\"  ' the returned directory needs a trailing backslash

'           These steps will jump to the other sub procedure to make the desired folders
            MakeNewDir _
                BaseDirectory:=strBaseDirectory, _
                AddDirectory:="FolderA"

            strA_Dir = strBaseDirectory & "FolderA" & "\"

            MakeNewDir _
                BaseDirectory:=strA_Dir, _
                AddDirectory:="Folder1"
            MakeNewDir _
                BaseDirectory:=strA_Dir, _
                AddDirectory:="Folder2"

            MakeNewDir _
                BaseDirectory:=strBaseDirectory, _
                AddDirectory:="FolderB"

            StrB_Dir = strBaseDirectory & "FolderB" & "\"

            MakeNewDir _
                BaseDirectory:=StrB_Dir, _
                AddDirectory:="Folder3"
            MakeNewDir _
                BaseDirectory:=StrB_Dir, _
                AddDirectory:="Folder4"

        End If
    End With


End Sub

Public Sub MakeNewDir(ByVal BaseDirectory As String, ByVal AddDirectory As String)
    If Dir(BaseDirectory, vbDirectory) = vbNullString Then
        MkDir BaseDirectory
    End If
    If Right(BaseDirectory, 1) <> "\" Then
        BaseDirectory = BaseDirectory & "\"
    End If
    MkDir BaseDirectory & AddDirectory
End Sub