2

我有以下代码,我想获取水平列出的各个文件夹中的文件。如何修改此代码,以便对于 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
4

2 回答 2

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 是函数参数,用于控制结果输出的起始位置。Range("A5") 给出起始文件夹名称,如 C:\temp,Range("B5") 是列出控制键的子文件夹,1=true,0=false。

在此处输入图像描述=========>

在此处输入图像描述

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

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

于 2013-11-14T22:26:09.563 回答
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
于 2013-11-14T21:37:12.437 回答