2
2

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 1 year has passed since last update.

AccessのVBAで外部テキストファイルを1行ずつ読み込み

Last updated at Posted at 2024-03-28

概要

txtやcsvなど テキストエディターで開けるファイル を1行ずつ読み込んで処理。

参照設定

Microsoft ActiveX Data Objects 2.8 Library
image.png

サンプル(1行目だけ)

'フォームにbtn_1というボタンがあり、そのクリックイベントという想定。
Private Sub btn_1_Click()


    Dim stream_ As New ADODB.Stream
    
    'OpenはLoadFromFileより前に行っておく必要があるので注意。
    'LoadFromFile ⇒ Openの順だと例外になります。
    stream_.Open

    stream_.Charset = "UTF-8"
    'SJISの場合は下記。
    'stream_.Charset = "SJIS"
    
    'キャリッジリターンラインフィード来た = 行末まで来た と判定。
    stream_.LineSeparator = adCRLF
    
    'Accessと同じフォルダーにあるtes.txtを読み込む。
    stream_.LoadFromFile CurrentProject.Path & "\tes.txt"
    
    '1行目だけ取り出して内容確認。
    Dim first_row_ As String
    first_row_ = stream_.ReadText(adReadLine)
    Debug.Print first_row_
    
    stream_.Close

    
End Sub

tes.txtが下記の時…
image.png

実行結果。
image.png

サンプル(全行)

Private Sub btn_1_Click()


    Dim stream_ As New ADODB.Stream
    stream_.Open
    stream_.Charset = "UTF-8"
    stream_.LineSeparator = adCRLF
    stream_.LoadFromFile CurrentProject.Path & "\tes.txt"

    Do Until stream_.EOS
        Debug.Print stream_.ReadText(adReadLine)
    Loop
    
    stream_.Close

    
End Sub

参考サイトさん

バージョン

Microsoft Windows [Version 10.0.19045.4239]
Microsoft Access for Microsoft 365 MSO (バージョン 2403 ビルド 16.0.17425.20138) 32 ビット

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?