How to restart a file input loop
I have this sample code in VBA:
iFileNum = FreeFi开发者_开发知识库le()
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?
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.
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)
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).
精彩评论