LoginSignup
11
13

More than 5 years have passed since last update.

VBAマクロでファイル一覧を再帰的に取得するFunctionプロシージャを作成してみた。

Posted at

VBAでファイル一覧を再帰的に取得するFunctionプロシージャを作成しました。
ネットの海をさまよってもSubプロシージャしか見当たらないので、これは自作するしか無いなと。

なお、FileSystemObjectを使用しているので、参照設定に「Microsoft Scripting Runtime」を設定して下さい。

ソースコード

fileutil.cls
Option Explicit

Private m_fso As FileSystemObject
Private m_files As Collection

Property Get FSO() As FileSystemObject
    Set FSO = m_fso
End Property

Property Get Files() As Collection
    Set Files = m_files
End Property

' ファイル一覧を再帰的に取得する関数
' 引数: folder_path 取得する起点のフォルダ
' 引数: pattern 取得対象のパターン(正規表現)
Public Function getFileListRecursive(folder_path As String, Optional pattern As String = "") As FileUtil
    ' ファイル一覧の結果格納用
    Dim file_list_tmp As Collection

    ' ループ用変数の宣言
    Dim folder As Variant
    Dim file_path As Variant
    Dim dir As Variant

    ' オブジェクトの初期化
    Set file_list_tmp = New Collection

    ' 現在ディレクトリ内の全ファイルの取得
    For Each file_path In FSO.GetFolder(folder_path).Files
        If file_path Like "*" & pattern & "*" Then
            DoEvents    ' フリーズ防止用
            Call Files.Add(CStr(file_path))
        End If
    Next

    ' サブディレクトリの再帰
    For Each dir In FSO.GetFolder(folder_path).SubFolders
        Call getFileListRecursive(dir.Path, pattern)
    Next


    Set getFileListRecursive = Me
End Function

' メンバ変数の初期化
Private Sub Class_Initialize()
    Set m_fso = New FileSystemObject
    Set m_files = New Collection
End Sub

' メンバ変数の解放
Private Sub Class_Terminate()
    Set m_fso = Nothing
    Set m_files = Nothing
End Sub

使用方法

sample.bas
Dim fu As FileUtil
Dim file As Variant
Set fu = New FileUtil

' 結果格納用変数
Dim result As Collection

' your_path配下でsearch_patternに合致した情報を取得
Set result = fu.getFileListRecursive("your_path", "search_pattern").Files ' 第二引数を省略した場合は全取得

' ファイル一覧がフルパスで表示される
For Each file In result
  ' 好きな処理を記述
  Debug.Print(file)
Next
11
13
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
11
13