Excel VBA 逆引き集 | テキストファイルを1行ずつ読む

Excel VBA
スポンサーリンク

テキストファイルを1行ずつ読む

テキストを「1行ずつ」読み込むと、ログやCSV/TSVの逐次処理、欠損補完、フィルタリングが自在にできます。初心者向けに最短コードから、安全なテンプレ、UTF-8対応までを整理します。


基本:Line Inputで1行ずつ読む

Sub ReadText_LineInput()
    Dim fn As Integer, line As String
    fn = FreeFile
    Open "C:\Data\sample.txt" For Input As #fn
    Do Until EOF(fn)
        Line Input #fn, line   '1行取得(改行は含まない)
        Debug.Print line       'ここで加工・判定など
    Loop
    Close #fn
End Sub
VB
  • ポイント: FreeFileで空きファイル番号を取得→Openで入力専用→EOFで終端までループ→Line Inputで1行取得という流れが定石です。

応用:行をシートへ順次書き込む

Sub ReadText_ToSheet()
    Dim fn As Integer, line As String, r As Long
    fn = FreeFile: Open "C:\Data\log.txt" For Input As #fn
    r = 2
    Do Until EOF(fn)
        Line Input #fn, line
        Cells(r, 1).Value = line
        r = r + 1
    Loop
    Close #fn
End Sub
VB
  • ポイント: Line Inputは読み取り位置を次行へ進めるので、そのままループすれば全行を取り込めます。

FSOで1行ずつ読む(ReadLine)

Sub ReadText_FSO()
    Dim fso As Object, ts As Object, r As Long
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.OpenTextFile("C:\Data\sample.txt", 1) '1=ForReading
    r = 2
    Do Until ts.AtEndOfStream
        Cells(r, 1).Value = ts.ReadLine
        r = r + 1
    Loop
    ts.Close
End Sub
VB
  • ポイント: FileSystemObjectのTextStream.ReadLineで1行取得、AtEndOfStreamで終端判定。構造が分かりやすく、可読性重視のときに向きます。

UTF-8を扱う(ADODB.Stream)

Sub ReadText_UTF8_Stream()
    Dim st As Object, text As String, lines As Variant
    Set st = CreateObject("ADODB.Stream")
    st.Type = 2                  'adTypeText
    st.Charset = "UTF-8"         '文字コードを指定
    st.Open
    st.LoadFromFile "C:\Data\utf8.txt"
    text = st.ReadText
    st.Close

    lines = Split(text, vbCrLf)
    Dim i As Long, r As Long
    r = 2
    For i = LBound(lines) To UBound(lines)
        If Len(lines(i)) > 0 Then
            Cells(r, 1).Value = lines(i)
            r = r + 1
        End If
    Next i
End Sub
VB
  • ポイント: ADODB.Streamは文字コード(UTF-8など)を指定して安定読込でき、BOM付きでも崩れにくいのが利点です。

安全テンプレート(存在確認+エラーハンドリング)

Sub ReadText_SafeTemplate()
    Dim path As String, fn As Integer, line As String
    path = ThisWorkbook.Path & "\input.txt"
    If Dir(path) = "" Then
        MsgBox "ファイルが見つかりません: " & path, vbExclamation
        Exit Sub
    End If

    On Error GoTo Fail
    fn = FreeFile
    Open path For Input As #fn
    Do Until EOF(fn)
        Line Input #fn, line
        '…加工・書き込み…
    Loop
    Close #fn
    Exit Sub

Fail:
    If fn <> 0 Then Close #fn
    MsgBox "読み込みに失敗しました: " & Err.Description, vbCritical
End Sub
VB
  • ポイント: Dirで存在確認→FreeFile/EOF/Line Inputの定石→失敗時もCloseを保証するのが安全運用です。

例題で練習

例題1:CSVの各行をSplitして列に展開

Sub Example_ReadCsvToColumns()
    Dim fn As Integer, line As String, parts As Variant, r As Long, i As Long
    fn = FreeFile: Open "C:\Data\data.csv" For Input As #fn
    r = 2
    Do Until EOF(fn)
        Line Input #fn, line
        parts = Split(line, ",")
        For i = LBound(parts) To UBound(parts)
            Cells(r, i + 1).Value = parts(i)
        Next i
        r = r + 1
    Loop
    Close #fn
End Sub
VB
  • ヒント: ダブルクォート内のカンマなど厳密CSVにはOpenText/QueryTables推奨。Line Input+Splitは簡易CSVやログ向きです。

例題2:キーワードで行を抽出し、該当だけ貼り付け

Sub Example_FilterLinesByKeyword()
    Dim fn As Integer, line As String, r As Long
    fn = FreeFile: Open "C:\Data\app.log" For Input As #fn
    r = 2
    Do Until EOF(fn)
        Line Input #fn, line
        If InStr(line, "ERROR") > 0 Then
            Cells(r, 1).Value = line
            r = r + 1
        End If
    Loop
    Close #fn
End Sub
VB

例題3:FSOで行番号付きにして出力

Sub Example_FSO_Numbered()
    Dim fso As Object, ts As Object, r As Long, s As String
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.OpenTextFile("C:\Data\event.log", 1)
    r = 2
    Do Until ts.AtEndOfStream
        s = ts.ReadLine
        Cells(r, 1).Value = r - 1 & ": " & s
        r = r + 1
    Loop
    ts.Close
End Sub
VB
  • 補足: ReadLine/AtEndOfStreamの組み合わせは、1行ずつ加工するロジックを組みやすいです。

落とし穴と対策

  • 文字コードの違いで文字化け: UTF-8はADODB.StreamでCharsetを指定して読むと安定します。
  • ファイル終端判定の不備: EOFやAtEndOfStreamで明確に終わりを判定してループを抜けるのが基本です。
  • ファイル番号の競合: FreeFileで番号を取得し、必ずCloseすることでトラブル回避。
  • 厳密CSVの仕様対応: ダブルクォート内のカンマ/改行はLine Input+Splitでは破綻しやすい。必要ならOpenText/QueryTablesへ切替が安全。

タイトルとURLをコピーしました