0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

VBAでファイルを読み込む

Last updated at Posted at 2022-03-08

VBAでファイルを読み込む

テキストファイルを読み込むにはOpenしてLine Inputで一行ずつ読み込む。
ただしVBAの外部ファイルはSJISを想定しているためUTF8のファイルを文字化けせずに読み込むことはできない。

Sub readfile(filepath As String)
    Dim buf As String
    Open filepath For Input As #1
        While Not EOF(1)
            Line Input #1, buf
            Debug.Print buf
        Wend
    Close #1
End Sub

VBAでUTF8のファイルを読み込む

ADODB.Stream オブジェクトを使用してファイルを読み込む。
ReadTextでファイルを一括して読み込む。

または.ReadText(adReadLine)で一行ずつ読み込み
.EOSでファイルの終了を検知する。
.EOSの検知するのは.ReadTextより先に判定する。

Sub readutf8file(filepath As String)
    Dim buf As String
    Dim line() As String
    
    ' read file block
    With CreateObject("ADODB.Stream")
        .Charset = "UTF-8"
        .Open
        .LoadFromFile filepath
        buf = .ReadText
        .Close
    End With
    
    ' separate crlf
    line = Split(buf, vbCrLf)
    Dim i As Integer
    For i = 0 To UBound(line) - 1
        Debug.Print line(i)
    Next
End Sub

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?