VBA宏列出多个文件夹中的文件

时间:2013-11-14 20:52:33

标签: excel vba file directory

我有以下代码,我希望水平列出各种文件夹中的文件。如何修改此代码,以便对于A列中的给定文件路径,我从C列开始获取此列中的文件?我的知识只允许我为一个文件夹(而不是我希望它查看的150个)


`enter code here`
Sub ListFiles()
  iCol = 3
  Call ListMyFiles(Range("A5"), Range("B5"))
End Sub

Sub ListMyFiles(mySourcePath, IncludeSubfolders)
    Set MyObject = New Scripting.FileSystemObject
    Set mySource = MyObject.GetFolder(mySourcePath)
    On Error Resume Next
    For Each myFile In mySource.Files
        iRow = 5

        Cells(iRow, iCol).Value = myFile.Name
        iCol = iCol + 1

    Next
    If IncludeSubfolders Then
        For Each mySubFolder In mySource.SubFolders
            Call ListMyFiles(mySubFolder.Path, True)
        Next

    End If
End Sub

2 个答案:

答案 0 :(得分:1)

我在Excel 2007中对此进行了测试:

Sub ListMyFiles(mySourcePath, IncludeSubfolders, iRow, iCol)
  Dim iColNow, iColSub
  Dim MyObject, mySource, myFile, mySubFolder
  Set MyObject = CreateObject("Scripting.FileSystemObject")
  Set mySource = MyObject.GetFolder(mySourcePath)
  On Error Resume Next
  iColNow = iCol
  For Each myFile In mySource.Files
    Cells(iRow, iColNow).Value = myFile.Name
    iColNow = iColNow + 1
  Next
  If IncludeSubfolders Then
    '
    'iColSub = iCol + 1
    '
    iColSub = iCol
    For Each mySubFolder In mySource.SubFolders
      iRow = iRow + 1
      Call ListMyFiles(mySubFolder.Path, IncludeSubfolders, iRow, iColSub)
    Next
  End If
End Sub

Sub ListFiles()
  Dim iRow, iCol
  iRow = 5
  iCol = 3
  Call ListMyFiles(Range("A5"), Range("B5"), iRow, iCol)
End Sub

IRow和iCol是控制结果输出起始位置的函数参数。 范围(“A5”)给出起始文件夹名称,如C:\ temp,Range(“B5”)是列出控制键的子文件夹,1 = true,0 = false。

enter image description here ========>

enter image description here

将为包含文件条目的文件夹创建一个空白行。

iRow以递归方式修改,以便更改每个子文件夹的行。

答案 1 :(得分:0)

'it's all in iRow
`enter code here`
Dim iRow as integer
Sub ListFiles()
  iCol = 3
  iRow = 5
  Call ListMyFiles(Range("A5"), Range("B5"))
End Sub

Sub ListMyFiles(mySourcePath, IncludeSubfolders)
    Set MyObject = New Scripting.FileSystemObject
    Set mySource = MyObject.GetFolder(mySourcePath)
    On Error Resume Next
    For Each myFile In mySource.Files


        Cells(iRow, iCol).Value = myFile.Name
        iCol = iCol + 1              
    Next
    iRow = iRow + 1 
    If IncludeSubfolders Then
        For Each mySubFolder In mySource.SubFolders
            Call ListMyFiles(mySubFolder.Path, True)
        Next

    End If
End Sub