2013-03-20 104 views
12

我有以下的,以逐行读取一个文件行:如何在VB脚本中逐行读取文件?

wscript.echo "BEGIN" 

filePath = WScript.Arguments(0) 
filePath = "C:\Temp\vblist.txt" 
Set ObjFso = CreateObject("Scripting.FileSystemObject") 
Set ObjFile = ObjFso.OpenTextFile(filePath) 
StrData = ObjFile.ReadLine 
wscript.echo "END OF FIRST PART" 

Do Until StrData = EOF(ObjFile.ReadLine) 
    wscript.echo StrData 
    StrData = ObjFile.ReadLine 
Loop 

wscript.echo "END" 

EOF()功能似乎并没有工作:

C:\Users\EGr\Documents\Scripts\VB>cscript testloop.vbs ArgVal 
Microsoft (R) Windows Script Host Version 5.8 
Copyright (C) Microsoft Corporation. All rights reserved. 

BEGIN 
END OF FIRST PART 
C:\Users\EGr\Documents\Scripts\VB\testloop.vbs(11, 1) Microsoft VBScript runti 
me error: Type mismatch: 'EOF' 

我没有在VB编程之前,但我m试图找出循环,以便我可以修改我已交给的VB脚本。我想逐行读取文件,并对每行执行一些操作。如果我改变做,直到环路Do Until StrData = EOF,当它到达了文件的末尾它的工作原理,但抛出一个错误:

C:\Users\EGr\Documents\Scripts\VB>cscript testloop.vbs ThisRANDOMValue 
Microsoft (R) Windows Script Host Version 5.8 
Copyright (C) Microsoft Corporation. All rights reserved. 

BEGIN 
1 
END OF FIRST PART 
host1 
host2 
host3 
C:\Users\EGr\Documents\Scripts\VB\testloop.vbs(13, 2) Microsoft VBScript runti 
me error: Input past end of file 

我觉得可能有一个简单的解决方案,但我一直没能找到它。我尝试了一些我在网上找到的其他解决方案,但还没有像上面那样接近。

回答

23

如有疑问,请阅读documentation

filename = "C:\Temp\vblist.txt" 

Set fso = CreateObject("Scripting.FileSystemObject") 
Set f = fso.OpenTextFile(filename) 

Do Until f.AtEndOfStream 
    WScript.Echo f.ReadLine 
Loop 

f.Close 
+0

谢谢!出于好奇,这是视觉基础,对吗?当我尝试做'Dim TestString As String ='看看这些!''它会为“预期的语句结束”引发错误 – EGr 2013-03-21 15:47:09

+4

它是VBScript,而不是VB。前者不支持“Dim variable As type”形式的变量声明。只需使用'Dim variable'而不需要在VBScript中声明变量的类型。 – 2013-03-21 16:23:05

+0

对不起所有的问题,但都是.vb和.vbs文件VBScript?我有两个文件类型。 – EGr 2013-03-21 17:53:55

0

如果像我这样的人被搜索到只读一个特定的线路,例如只有18行这里是代码:

filename = "C:\log.log" 

Set fso = CreateObject("Scripting.FileSystemObject") 
Set f = fso.OpenTextFile(filename) 

For i = 1 to 17 
    f.ReadLine 
Next 

strLine = f.ReadLine 
Wscript.Echo strLine 

f.Close