Excel VBAでUTF-8テキストを読み込む簡単マクロ【相対パス対応】

Excel VBAでUTF-8のテキストファイルを読み込むには、ADODB.Stream を使うのが便利です。以下は、マクロファイルと同じフォルダにある text.txt を読み込み、A列に1行ずつ表示するマクロです。

Sub LoadUtf8Text_RelativePath()
    Dim stream As Object, text As String, lines As Variant, i As Long
    Dim filePath As String: filePath = ThisWorkbook.Path & "\text.txt"

    Set stream = CreateObject("ADODB.Stream")
    With stream
        .Charset = "utf-8": .Open
        .LoadFromFile filePath
        text = .ReadText(-1): .Close
    End With

    lines = Split(text, vbCrLf)
    For i = 0 To UBound(lines)
        Cells(i + 1, 1).Value = lines(i)
    Next i

    MsgBox "読み込み完了:" & vbCrLf & filePath
End Sub

Comments

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です