指定したフォルダの配下にあるファイルを再帰的に探索し、ファイルパスの一覧を配列に格納したい場合、たとえば以下のようなサブルーチンを定義すればよいです。
' 指定したフォルダの配下にあるファイルパスの一覧を取得し、filePaths配列に格納する
' サブフォルダがある場合も再帰的に探索する。
Sub walkFileTree(folderPath As String, ByRef filePaths As Collection)
Dim FSO, childFile, childFolder
Set FSO = CreateObject("Scripting.FileSystemObject")
' 指定したフォルダの直下にファイルがある場合、そのパスをfilePaths配列に格納する
For Each childFile In FSO.GetFolder(folderPath).Files
filePaths.Add childFile.Path
Next childFile
' 指定したフォルダの直下にフォルダがある場合、そのフォルダを頂点に再帰的に探索を行う
For Each childFolder In FSO.GetFolder(folderPath).SubFolders
walkFileTree childFolder.Path, filePaths
Next childFolder
End Sub
使用例です。次のような構成のC:\START
フォルダがあるとします。
C:\>tree start /F
フォルダー パスの一覧: ボリューム Windows
ボリューム シリアル番号は ACA7-872F です
C:\START
│ a.txt
│
├─dir1
│ b.txt
│ c.txt
│
└─dir2
│ d.txt
│
└─dir3
e.txt
f.txt
C:\START
フォルダ配下のファイルパス一覧を再帰的に取得したい場合、walkFileTree
サブルーチンを以下のように利用します。
Sub Main()
Dim folderPath As String
Dim filePaths As Collection
folderPath = "C:\START"
Set filePaths = New Collection
Call walkFileTree(folderPath, filePaths)
Dim filePath As Variant
For Each filePath In filePaths
Debug.Print filePath
Next filePath
End Sub
実行結果は以下のようになります。
C:\start\a.txt
C:\start\dir1\b.txt
C:\start\dir1\c.txt
C:\start\dir2\d.txt
C:\start\dir2\dir3\e.txt
C:\start\dir2\dir3\f.txt