Sub ImportMultipleCSV()
Dim csvFiles As Variant
Dim i As Long
Dim lastRow As Long
Dim tempWB As Workbook
Dim targetWS As Worksheet
' 複数CSVファイルを選択
csvFiles = Application.GetOpenFilename("CSVファイル (*.csv),*.csv", _
Title:="CSVファイルを選択(複数可)", _
MultiSelect:=True)
If VarType(csvFiles) = vbBoolean Then
MsgBox "キャンセルされました。", vbExclamation
Exit Sub
End If
Set targetWS = ThisWorkbook.Sheets(1) ' 貼り付け先は1枚目のシートとする
targetWS.Cells.Clear ' 事前にクリア
Application.ScreenUpdating = False
For i = LBound(csvFiles) To UBound(csvFiles)
Set tempWB = Workbooks.Open(Filename:=csvFiles(i), ReadOnly:=True)
' 貼り付け先の最後の行を取得
lastRow = targetWS.Cells(targetWS.Rows.Count, 1).End(xlUp).Row
If lastRow > 1 Or targetWS.Cells(1, 1).Value <> "" Then
lastRow = lastRow + 1
End If
' コピー&貼り付け
tempWB.Sheets(1).UsedRange.Copy Destination:=targetWS.Cells(lastRow, 1)
tempWB.Close SaveChanges:=False
Next i
Application.ScreenUpdating = True
MsgBox "CSVファイルの読み込みが完了しました!", vbInformation
End Sub
コメント