How to restart a file input loop

11,243

Solution 1

The FileSystemObject Object might give you more control:

''Library: Windows Script Host Object Model
Dim fso, ts
Const ForReading = 1

Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.OpenTextFile("c:\docs\test.txt", ForReading, True)
a = ts.Readall

Debug.Print a
aa = Split(a, vbCrLf)
Debug.Print aa(0)

Solution 2

I believe you can use it:

    If EOF(fileNum) Then
        Seek fileNum, 1
    End If

Seek command moves the pointer to anywhere in the file.. so the 1 moves the pointer to the start of the file.

Still, Ho1 answer above needs to be considered.

Solution 3

If you meant that you want to read another file, then you have to close this file and open the other file. Otherwise, if you mean that you want to read the same file again, then that's the same that you will have to close it and re-open it.
However, I'd suggest that in that case you just cache the contents of the file in memory rather than reading it multiple times (unless the content of it has changed of course).

Share:
11,243
JOE SKEET
Author by

JOE SKEET

Updated on June 28, 2022

Comments

  • JOE SKEET
    JOE SKEET almost 2 years

    I have this sample code in VBA:

       iFileNum = FreeFile()
       Open fileLocation For Input As #1
       Do While Not EOF(iFileNum)
         Line Input #iFileNum, sText
    
       Loop
    

    How do I restart iFileNum to go back to the beginning of the file?