2013-03-20 106 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