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?

Excel VBA 任意フォルダ内のファイル情報を取得しリストアップする

Posted at

はじめに

指定したフォルダ内のファイル情報を取得しリストアップする。

プロシジャーの説明

サブフォルダも3階層まで調べることができます。このコードは、指定フォルダ内とそのサブフォルダ内のファイル情報(ファイル名、パスなど)をリストアップするものです。

サンプル1

Option Explicit

Sub GetFolderFileInfo()
' -------------------------------------------------------------
' 指定したフォルダ内のファイル情報を取得し、
' サブフォルダも3階層まで調べることができます。
' このコードは、指定フォルダ内とそのサブフォルダ内のファイル情報
' (ファイル名、パスなど)をリストアップするものです。
' -------------------------------------------------------------
    Dim FolderPath As String
    Dim ws As Worksheet
    Dim RowIndex As Long
    
    ' フォルダパスを指定
    FolderPath = "C:\ALLlib\エクセルマクロ"
    Set ws = ThisWorkbook.Sheets(1) ' 結果を出力するシート
    RowIndex = 1 ' データの開始行
    
    ' シートのヘッダー
    ws.Cells(RowIndex, 1).Value = "ファイル名"
    ws.Cells(RowIndex, 2).Value = "ファイルパス"
    RowIndex = RowIndex + 1
    
    ' フォルダ内のファイルをリスト化
    Call ListFiles(FolderPath, ws, RowIndex, 1)
    
    MsgBox "完了しました!"
End Sub

Sub ListFiles(ByVal FolderPath As String, ByRef ws As Worksheet, ByRef RowIndex As Long, ByVal Depth As Integer)
    Dim FSO As Object
    Dim Folder As Object
    Dim SubFolder As Object
    Dim File As Object
    
    ' FileSystemObjectを設定
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set Folder = FSO.GetFolder(FolderPath)
    
    ' フォルダ内のファイルを取得
    For Each File In Folder.Files
        ws.Cells(RowIndex, 1).Value = File.Name
        ws.Cells(RowIndex, 2).Value = File.Path
        RowIndex = RowIndex + 1
    Next File
    
    ' サブフォルダを再帰的に処理 (3階層まで)
    If Depth < 3 Then
        For Each SubFolder In Folder.Subfolders
            Call ListFiles(SubFolder.Path, ws, RowIndex, Depth + 1)
        Next SubFolder
    End If
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?