Excel文件目录抓取器

时间:2017-02-03 06:44:39

标签: excel vba directory

目前我有一个专门用于索引文件夹的工作簿,您可以在其中输入文件夹路径,例如'Z:\ Example',它将该特定文件夹中所有内容的所有文件名和文件路径导出到工作簿中的另一个工作表中。我想知道是否有可能获取该文件夹中的所有文件('Z:\ Example'),如果该目录中还有其他任何文件夹,也可以获取该文件夹中的所有文件。

  

E.g。我在单元格A19中输入'Z:\ Example'(根据下面的代码),   'Z:\ Example'中有另一个文件夹,Z:\ Example \ Another'。所有的文件   在'Z:\ Example'和Z:\ Example \ Another'中加入   excel表2.

Private Sub CommandButton1_Click()

    Dim objFSO As Object
    Dim objFolder As Object
    Dim objFile As Object
    Dim i As Integer
    Dim Source_Workbook As Workbook
    Dim Target_Path As String

    'Create an instance of the FileSystemObject
    Set objFSO = CreateObject("Scripting.FileSystemObject")

    'Path of the Target Folder
    Target_Path = Range("A19").Value

    Set Target_Workbook = Workbooks.Open(Target_Path)
    Set Source_Workbook = ThisWorkbook

    'Get the folder object

    Set objFolder = objFSO.GetFolder(Target_Path)
    i = 1
    'loops through each file in the directory and prints their names and path

    For Each objFile In objFolder.Files
        'print file name
        Source_Workbook.Sheets(2).Cells(i + 1, 1) = objFile.Name
        'print file path
        Source_Workbook.Sheets(2).Cells(i + 1, 2) = objFile.Path
        i = i + 1
    Next objFile

    'Process Completed
    msgBox "Task Completed"
End Sub

我宁愿不必在开头插入我想要索引的所有路径,但如果这是不可避免的,那就没关系。任何帮助表示赞赏。

由于

1 个答案:

答案 0 :(得分:0)

在评论中,列出文件夹及其子文件夹的资源很多。此代码段是根据您的应用程序自定义的。它使用递归,需要输入根文件夹和目标单元格来粘贴结果。

Private Sub CommandButton1_Click()
    'Call the recursive function
    ListAllFiles ThisWorkbook.Sheets(1).Range("A19").Value, ThisWorkbook.Sheets(2).Cells(2, 1)
    msgBox "Task Completed"
End Sub


Private Sub ListAllFiles(root As String, targetCell As Range)
    Dim objFSO As Object, objFolder As Object, objSubfolder As Object, objFile As Object
    Dim i As Integer, Target_Path As String

    'Create an instance of the FileSystemObject
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    'Get the folder object
    Set objFolder = objFSO.GetFolder(root)
    'loops through each file in the directory and prints their names and path

    For Each objFile In objFolder.Files
        'print file name
        targetCell.Value = objFile.Name
        'print file path
        targetCell.Offset(, 1).Value = objFile.Path
        Set targetCell = targetCell.Offset(1)
    Next objFile

    ' Recursively call the function for subfolders
    For Each objSubfolder In objFolder.SubFolders
        ListAllFiles objSubfolder.Path, targetCell
    Next objSubfolder
End Sub