2

次のコードがあり、横方向にリストされたさまざまなフォルダー内のファイルを取得したいと考えています。列 A の特定のファイル パスに対して、この列のファイルを列 C 以降に取得するように、このコードを修正するにはどうすればよいですか? 私の知識では、1つのフォルダーに対してのみ実行できます(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 に答える