0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

指定したフォルダにあるファイルを再帰的に探索したい

Posted at

指定したフォルダの配下にあるファイルを再帰的に探索し、ファイルパスの一覧を配列に格納したい場合、たとえば以下のようなサブルーチンを定義すればよいです。

' 指定したフォルダの配下にあるファイルパスの一覧を取得し、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
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?