[VBA] ファイルとフォルダのリストを取得する

指定したフォルダ内のファイル名を取得し、Debug.Printで表示します。

Sub filelist()

    Dim files As Collection
    Dim fileName As Variant
    
    Set files = GetFileList(ThisWorkbook.Path)
    
    For Each fileName In files
        Debug.Print fileName
    Next fileName

End Sub

関数「GetFileList」は、指定したフォルダ内のファイル名を取得します。

パラメータ:
includeFolders (オプション): フォルダを含めるかどうかを指定するフラグ。デフォルトはFalse
folderPath: ファイルを取得するフォルダーパス。

Function GetFileList(folderPath As String, Optional includeFolders As Boolean = False) As Collection

    Dim filelist As New Collection
    Dim filePath As String
    
    ' フォルダパス
    If Right(folderPath, 1) <> "\" Then folderPath = folderPath & "\"
    
    ' Dir
    filePath = Dir(folderPath & "*", vbNormal Or vbDirectory)
    
    Do While filePath <> ""
        
        If filePath <> "." And filePath <> ".." Then
            
            If (GetAttr(folderPath & filePath) And vbDirectory) = vbDirectory Then
                ' フォルダの場合
                If includeFolders Then filelist.Add filePath
            Else
                ' ファイルの場合
                filelist.Add filePath
            End If
        End If
        
        filePath = Dir
    Loop
    
    Set GetFileList = filelist

End Function

VBA

Posted by kidatti