マイナー・マイナー

隠れた名作の発掘が生きがい。

【VBA】ファイルとフォルダのリストを再帰的に取得する


スポンサードリンク

VBAで特定のフォルダを指定すると、その配下のファイルとフォルダの一覧を取得する関数を作成しました。BShellでいう「find . -type f」や「find . -type d」の実行結果を得るような関数です。

''' 指定されたフォルダ配下を再帰的に検索し、ファイル名リストとフォルダ名リストを作成する
Private Sub GetFileAndFolderNameList(ByVal targetFolder As Folder, ByRef fileList As Collection, ByRef folderList As Collection)
    Dim childFolder As Folder
    Dim targetFile As File
  
    For Each targetFile In targetFolder.Files
        fileList.Add (targetFile.Path)
    Next targetFile
  
    For Each childFolder In targetFolder.SubFolders
        folderList.Add (childFolder.Path)
        Call GetFileAndFolderNameList(childFolder, fileList, folderList)
    Next childFolder
End Sub


実行には「Microsoft Scripting Runtime」が必要なので、VBAのTools->Referencesより「Microsoft Scripting Runtime」のチェックをつけておきます。上記の関数は、例えば下記のように呼び出します。

Sub ExtractFileAndFolderList()
    Dim inputRootDir As String
    inputRootDir = "C:\work"
  
    Dim fso As FileSystemObject
    Set fso = New FileSystemObject
  
    Dim fileList As Collection
    Set fileList = New Collection
    Dim folderList As Collection
    Set folderList = New Collection
  
    Call GetFileAndFolderNameList(fso.GetFolder(inputRootDir), fileList, folderList)
  
    Dim i As Integer
    Debug.Print ("fileList:")
    For i = 1 To fileList.Count
        Debug.Print (fileList(i))
    Next i
    Debug.Print ("folderList:")
    For i = 1 To folderList.Count
        Debug.Print (folderList(i))
    Next i
  
End Sub


例えばC:\work 配下に、下記のファイル、フォルダがあったとき、

\a.txt
\b.txt
\c.txt
\hoge
\hoge\a.txt
\hoge\b.txt
\hoge\c.txt
\hoge\moge
\hoge\moge\a.txt
\hoge\moge\b.txt
\piyo
\piyo\a.txt

ExtractFileAndFolderListを実行すると下記のような結果となりました。

fileList:
C:\work\a.txt
C:\work\b.txt
C:\work\c.txt
C:\work\hoge\a.txt
C:\work\hoge\b.txt
C:\work\hoge\c.txt
C:\work\hoge\moge\a.txt
C:\work\hoge\moge\b.txt
C:\work\piyo\a.txt
folderList:
C:\work\hoge
C:\work\hoge\moge
C:\work\piyo