5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Excel VBA] get the list of file path.

Last updated at Posted at 2014-05-09

FileListの中で呼んでいるGetFilePathList関数に適切に引数を渡してあげてください。

第1引数で指定したディレクトリ下を再帰的に検索し、第2引数で指定したファイル(ワイルドカードOK)
を、シートに全部書き出します。

Option Explicit

Sub FileList()
    Dim Files As Variant
    Files = GetFilePathList("c:\Samples", "*.pdf")
    
    Range(Cells(1, "A"), Cells(UBound(Files, 2), "B")) _
        = Application.WorksheetFunction.Transpose(Files)
End Sub

Private Function GetFilePathList(Path As String, Target As String) As Variant
    Dim FSO As Object, Folder As Variant, File As Variant
    Set FSO = CreateObject("Scripting.FileSystemObject")
    
    
    Dim Files() As Variant
    ReDim Preserve Files(1, 0)
    
    For Each Folder In FSO.GetFolder(Path).SubFolders
        Dim SubFiles() As Variant
        SubFiles = GetFilePathList(Folder.Path, Target)
        
        Dim FromIndex As Integer
        Dim ToIndex As Integer
        
        FromIndex = UBound(Files, 2)
        ToIndex = FromIndex + UBound(SubFiles, 2)
        ReDim Preserve Files(1, ToIndex)
        Dim i As Integer
        For i = FromIndex To ToIndex
            Files(0, i) = SubFiles(0, i - FromIndex)
            Files(1, i) = SubFiles(1, i - FromIndex)
        Next i
    Next Folder
    
    
    For Each File In FSO.GetFolder(Path).Files
        If File.Name Like Target Then
            ReDim Preserve Files(1, UBound(Files, 2) + 1)
            Files(0, UBound(Files, 2) - 1) = File.ParentFolder
            Files(1, UBound(Files, 2) - 1) = File.Name
        End If
    Next File
    
    GetFilePathList = Files
End Function

参考サイト

Office Tanaka(1)
Office Tanaka(2)
hiroaki's Lab

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?