Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read lines from a text file one by one with Power Point VBA code?

This code will read a line from a text file:

set file = CreateObject("Scripting.FileSystemObject").OpenTextFile("c:\number.txt", 1)
text = file.ReadLine
MsgBox text

How can I make it read repeatedly one line after another from the same file? I guess, I should use a loop here, right? I need it to read the first line from the file at the first iteration, the second line at the second iteration, the third one at the third and so on till all the lines have been read. How can I do it?

Important addition: I need the code to operate on each line one by one - not all at once!

like image 820
brilliant Avatar asked Jan 23 '23 00:01

brilliant


2 Answers

Use the ReadAll() method:

text = file.ReadAll

(Might be of interest: FileSystemObject Sample Code)

With a loop:

Const ForReading = 1, ForWriting = 2, ForAppending = 8
Dim fso, MyFile, FileName, TextLine

Set fso = CreateObject("Scripting.FileSystemObject")

FileName = "c:\testfile.txt"

Set MyFile = fso.OpenTextFile(FileName, ForReading)

'' Read from the file
Do While MyFile.AtEndOfStream <> True
    TextLine = MyFile.ReadLine

    '' Do stuff to TextLine

Loop
MyFile.Close
like image 196
Mitch Wheat Avatar answered Jan 31 '23 08:01

Mitch Wheat


If for some reason you want to use the in-built VBA file handling routines, you would use code like this:

Sub ReadAFileLineByLine()
    Dim InStream As Integer
    InStream = FreeFile()
    Open "C:/tmp/fastsynchtoquesttry_quest.txt" For Input As InStream

    Dim CurrLine As String
    Do While True
        Line Input #InStream, CurrLine
        ' do stuff to CurrLine
        If EOF(InStream) Then Exit Do
    Loop

    Close #InStream
End Sub
like image 26
Jon Fournier Avatar answered Jan 31 '23 10:01

Jon Fournier