CSV統合の応用版テンプレート
今回は 「統合時にファイル名を列として追加する版」 と 「複数フォルダを対象にする版」 を紹介します。
1. 統合時にファイル名を列として追加する版
各CSVのデータを統合するときに、元ファイル名を列として追加しておくと、後から「どのデータがどのファイル由来か」追跡できます。
Sub MergeCSV_AddFileNameColumn()
Dim folderPath As String, fileName As String
Dim wsMaster As Worksheet
Dim pasteRow As Long, lastRow As Long
folderPath = "C:\Data\CSV\" ' ←環境に合わせて変更
Set wsMaster = ThisWorkbook.Sheets("Master")
wsMaster.Cells.Clear
pasteRow = 1
fileName = Dir(folderPath & "*.csv")
Do While fileName <> ""
Dim wbCSV As Workbook, wsCSV As Worksheet
Set wbCSV = Workbooks.Open(folderPath & fileName)
Set wsCSV = wbCSV.Sheets(1)
lastRow = wsCSV.Cells(wsCSV.Rows.Count, 1).End(xlUp).Row
' データをコピー
wsCSV.Range("A1:A" & lastRow).EntireRow.Copy wsMaster.Cells(pasteRow, 1)
' ファイル名を右端列に追加
Dim copiedRows As Long
copiedRows = lastRow
wsMaster.Range(wsMaster.Cells(pasteRow, wsMaster.Cells(pasteRow, 1).End(xlToRight).Column + 1), _
wsMaster.Cells(pasteRow + copiedRows - 1, wsMaster.Cells(pasteRow, 1).End(xlToRight).Column + 1)).Value = fileName
pasteRow = wsMaster.Cells(wsMaster.Rows.Count, 1).End(xlUp).Row + 1
wbCSV.Close SaveChanges:=False
fileName = Dir
Loop
MsgBox "CSV統合完了!(ファイル名列付き)"
End Sub
VB2. 複数フォルダを対象にする版
複数のフォルダを対象にして、すべてのCSVを統合する例です。フォルダパスを配列で管理します。
Sub MergeCSV_MultiFolders()
Dim folders As Variant
Dim i As Long, folderPath As String, fileName As String
Dim wsMaster As Worksheet
Dim pasteRow As Long, lastRow As Long
folders = Array("C:\Data\CSV1\", "C:\Data\CSV2\", "D:\Backup\CSV\") ' ←対象フォルダを列挙
Set wsMaster = ThisWorkbook.Sheets("Master")
wsMaster.Cells.Clear
pasteRow = 1
For i = LBound(folders) To UBound(folders)
folderPath = folders(i)
fileName = Dir(folderPath & "*.csv")
Do While fileName <> ""
Dim wbCSV As Workbook, wsCSV As Worksheet
Set wbCSV = Workbooks.Open(folderPath & fileName)
Set wsCSV = wbCSV.Sheets(1)
lastRow = wsCSV.Cells(wsCSV.Rows.Count, 1).End(xlUp).Row
' データコピー
wsCSV.Range("A1:A" & lastRow).EntireRow.Copy wsMaster.Cells(pasteRow, 1)
' フォルダ名+ファイル名を右端列に追加
Dim copiedRows As Long
copiedRows = lastRow
wsMaster.Range(wsMaster.Cells(pasteRow, wsMaster.Cells(pasteRow, 1).End(xlToRight).Column + 1), _
wsMaster.Cells(pasteRow + copiedRows - 1, wsMaster.Cells(pasteRow, 1).End(xlToRight).Column + 1)).Value = folderPath & fileName
pasteRow = wsMaster.Cells(wsMaster.Rows.Count, 1).End(xlUp).Row + 1
wbCSV.Close SaveChanges:=False
fileName = Dir
Loop
Next i
MsgBox "複数フォルダのCSV統合完了!(フォルダ+ファイル名列付き)"
End Sub
VB✅ まとめ
- ファイル名列追加版 → 統合後に「どのファイル由来か」を追跡可能。
- 複数フォルダ対象版 → 複数のフォルダを一度に処理できる。

