Scripting.TextStreamでファイル読み込み@Excel マクロ・VBA

Scripting.TextStreamでファイル読み込みを行います。

Microsoft Scripting Runtimeを参照設定します。
Scripting.FileSystemObjectを生成します。
もしくは、参照設定せずにCreateObject("Scripting.FileSystemObject")です。

OpenTextFileメソッドにて、TextStreamオブジェクトを生成します。
OpenTextFile(ファイル名,読み取りモード,上書きモード,format)です。

formatは、
TristateFalse:ASCIIファイル
TristateTrue :Unicode
TristateUseDefault:システムの既定値
TristateMixed:混在
となります。

TextSreamオブジェクトを生成したら、
ファイルから読み込みを行います。

以下では、Do Whileでループし、
1行ずつ読み込んでいます。



Sub test()

Dim fileSystem As New Scripting.FileSystemObject
Dim textStream As Scripting.textStream

Dim rowNo As Integer

On Error GoTo Err

'FileSystemObject生成
Set fileSystem = New Scripting.FileSystemObject

'ファイルを開く
Set textStream = fileSystem.OpenTextFile("C:\test.txt", ForReading, False, TristateUseDefault)

rowNo = 1
'1行読み込み
Do While textStream.AtEndOfStream = False
    Worksheets("Sheet1").Cells(rowNo, 1).Value = textStream.ReadLine
    rowNo = rowNo + 1
Loop


'クローズ
textStream.Close
Set textStream = Nothing
Set fileSystem = Nothing

Exit Sub

Err:
'エラー
Set textStream = Nothing
Set fileSystem = Nothing
MsgBox (Err.Description)

End Sub




Copyright (C) Excelマクロ・VBAのお勉強. All Rights Reserved.