vba 如何重新启动文件输入循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4973678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 12:39:16  来源:igfitidea点击:

How to restart a file input loop

excel-vbado-whilefile-iovbaexcel

提问by JOE SKEET

I have this sample code in VBA:

我在 VBA 中有这个示例代码:

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

   Loop

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

如何重新启动iFileNum以返回到文件的开头?

回答by Tiago Cardoso

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.

Seek 命令将指针移动到文件中的任何位置。因此 1 将指针移动到文件的开头。

Still, Ho1 answer above needs to be considered.

尽管如此,需要考虑上面的Ho1答案。

回答by Fionnuala

The FileSystemObject Objectmight give you more control:

FileSystemObject对象可能会给你更多的控制权:

''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)

回答by Hans Olsson

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).

如果您的意思是要读取另一个文件,则必须关闭该文件并打开另一个文件。否则,如果您的意思是要再次读取同一个文件,那么您将不得不关闭它并重新打开它。
但是,我建议在这种情况下,您只需将文件的内容缓存在内存中,而不是多次读取它(除非它的内容当然已更改)。