つらつら Excel VBA

私の備忘録です。

複数のテキストファイルを読み込む処理

'参照設定 Microsoft Scripting Runtime
Sub 複数のテキストファイルを1行ずつ読み込む処理FSO()
    
    Dim tempFolder As String
    tempFolder = ThisWorkbook.Path & "\temp\"
    
    Dim f As File
    Dim ts As TextStream
    Dim fso As FileSystemObject
    Set fso = New FileSystemObject
    Dim buf As String
    Dim iRow As Long
    Dim iColmun As Long
    
    '新規シートを最後尾に挿入
    Dim sh As Worksheet
    Set sh = ThisWorkbook.Worksheets.Add(after:=Worksheets(Worksheets.Count))
    
    iColmun = 1
    
    For Each f In fso.GetFolder(tempFolder).Files
        
        iRow = 1
        Set ts = f.OpenAsTextStream
        
        Do While ts.AtEndOfStream <> True
            buf = ts.ReadLine
            sh.Cells(iRow, iColmun).Value = buf
            iRow = iRow + 1
        Loop
        
        ts.Close
        iColmun = iColmun + 1
        
    Next
    
    Set fso = Nothing
    Debug.Print "完了"
    
End Sub

以上。