項目

フォルダを検索する(Dir)

概要

Dirでフォルダを検索する事ができます。
例ではサブフォルダは検索しません。

Option Compare Database
Option Explicit

Private Sub コマンド0_Click()

    Dim pathname As String
    Dim filepath As String

    '@c\tempフォルダがあるか検索
    pathname = "c:\temp"

    filepath = Dir(pathname, vbDirectory)

    If filepath = "" Then
        Debug.Print "ないよ"
    Else
        Debug.Print "あるよ"
    End If

    'Ac:\tempの内のサブフォルダを検索
    pathname = "c:\temp\"

    '検索するファイルがあった場合ファイル名が格納される
    filepath = Dir(pathname, vbDirectory)

    Do Until filepath = ""

        If filepath <> "." And filepath <> ".." Then
            ' フォルダかどうかを調べる
            If (GetAttr(pathname & filepath) And vbDirectory) = vbDirectory Then
                Debug.Print filepath   'フォルダ名をイミディエイトウィンドウに出力
            End If
        End If

        '次のフォルダを検索
        filepath = Dir

    Loop

End Sub