【Excel VBA】CSVを読み込むマクロ

業務効率化
スポンサーリンク
  • 「hogehogehogehoge」という文字列を含むCSVをすべて読み込む。
  • CSVは同階層の「csv」フォルダに入っている。
  • CSVから読み込むのは2行目以降。
  • 読み込むシート名は「すべてのレコード」とする。
  • ログ!A2以降に読み込んだファイル名をすべて記載する。
  • マクロ実行の際は見出し以外をクリアした後に読み込むようにする。
Option Explicit

Sub ImportCSVFiles()

    Dim wb As Workbook
    Dim wsData As Worksheet
    Dim wsLog As Worksheet
    Dim folderPath As String
    Dim fileName As String
    Dim lastDataRow As Long
    Dim lastLogRow As Long
    Dim qt As QueryTable
    
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    
    '--- シートの参照 ---
    Set wb = ThisWorkbook
    Set wsData = wb.Sheets("すべてのレコード")
    Set wsLog = wb.Sheets("ログ")
    
    '--- csvフォルダのパス ---
    folderPath = wb.Path & "\csv\"
    
    '--- データシートの見出し以外をクリア ---
    lastDataRow = wsData.Cells(wsData.Rows.Count, 1).End(xlUp).Row
    If lastDataRow > 1 Then
        wsData.Rows("2:" & lastDataRow).ClearContents
    End If
    
    '--- ログシートの見出し以外をクリア ---
    lastLogRow = wsLog.Cells(wsLog.Rows.Count, 1).End(xlUp).Row
    If lastLogRow > 1 Then
        wsLog.Rows("2:" & lastLogRow).ClearContents
    End If
    
    '--- CSVファイルを順次読み込み ---
    fileName = Dir(folderPath & "*hogehogehogehoge*.csv")
    
    Dim dataRow As Long
    dataRow = 2       'データ貼付開始行
    
    Do While fileName <> ""
        Dim csvPath As String
        csvPath = folderPath & fileName
        
        '--- CSVをインポート ---
        With wsData.QueryTables.Add(Connection:="TEXT;" & csvPath, _
                                    Destination:=wsData.Cells(dataRow, 1))
            .TextFileParseType = xlDelimited
            .TextFileCommaDelimiter = True
            .TextFileColumnDataTypes = Array(1)
            .TextFileStartRow = 2        ' 2行目以降を読み込み
            .Refresh BackgroundQuery:=False
            .Delete                     ' QueryTableは不要なので削除
        End With
        
        '--- 次のデータ開始行を更新 ---
        dataRow = wsData.Cells(wsData.Rows.Count, 1).End(xlUp).Row + 1
        
        '--- ログにファイル名を追記 ---
        wsLog.Cells(wsLog.Cells(wsLog.Rows.Count, 1).End(xlUp).Row + 1, 1).Value = fileName
        
        '--- 次のファイルへ ---
        fileName = Dir
    Loop
    
    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
    
    MsgBox "CSVの読み込みが完了しました。", vbInformation

End Sub