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?

More than 3 years have passed since last update.

ディレクトリ検索

Last updated at Posted at 2022-03-08

VBAのディレクトリ検索

Dir()関数を使う。
Dir()関数は初回検索時に検索パスとファイルパターンを与え、2回目以降は引数を持たない。
Dir()関数の戻り値が””のときはそれ以上のファイルはない。
デフォルトではDir()は実ファイルしか検索しない。
またDir()は再帰的には呼べないので一度全部読みだす。

単純検索(サブディレクトリは検索しない)

Sub main()
    traverse ("D:\download")
End Sub

Sub traverse(path As String)
    Dim leaf As String
    leaf = Dir(path & "\*")
    While leaf <> ""
        Dim fullpath As String
        fullpath = path & "\" & leaf
        Debug.Print fullpath
        leaf = Dir()
    Wend
End Sub

再帰的検索

Dir()は再帰的に使用することができないためディレクトリは一気に読み込む必要がある。
Dir()の第二パラメータにいろいろなフラグを立てないとそのフラグを持つファイルが検索できない。
イメージとしては

検索該当 =(ファイルタイプビットマップ & ~検索タイプマスク) == 0

少なくともDir()の第二パラメータにvbDirectoryを指定しないと、ディレクトリは検索できない。
またこれによりDir()はファイルやディレクトリ以外のものも検索可能なため
実際に何が検索できたかどうかはGetAttr()にファイルパターンマスクのアンドと取って調べなくてはならない。
以下のソースのdir dealerとfile dealerにそれぞれ希望のファイル処理を実装または呼び出す。
dir dealerは特にディレクトリの処理に興味がなければなくてもよい。

Sub subtraverse(path As String)
    ReDim leafs(1)
    Dim i As Integer
    i = 0
    Dim leafnumber As Integer
    
    'scan directory
    Dim leaf As String
    leaf = Dir(path & "\*", vbNormal + vbHidden + vbReadOnly + vbSystem + vbDirectory)
    While leaf <> ""
        If UBound(leafs) < i Then
            ReDim Preserve leafs(2 * UBound(leafs))
        End If
        leafs(i) = leaf
        i = i + 1
        leaf = Dir()
    Wend
    leafnumber = i

    'deal directory
    For i = 0 To leafnumber - 1
        Dim fullpath As String
        fullpath = path & "\" & leafs(i)
        If GetAttr(fullpath) And vbDirectory Then
            If leafs(i) <> "." And leafs(i) <> ".." Then
                subtraverse (fullpath)
                ' dir dealer
                Debug.Print "dir ", fullpath
            End If
        Else
            ' file dealer
            Debug.Print "file", fullpath
        End If
    Next
End Sub
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?