在vbscript中读取文本文件的某一行

时间:2015-10-15 15:58:02

标签: vbscript

有没有办法使用vbscript读取文本文件的某一行并将其存储为变量。 感谢。

1 个答案:

答案 0 :(得分:2)

试试这个例子:

Option Explicit
Dim ws,MyFile
Set ws = CreateObject("WScript.Shell")
MyFile = "%Windir%\system32\slmgr.vbs"
MyFile = ws.ExpandEnvironmentStrings(MyFile)
wscript.echo ExtractLinesFromTextFile(Myfile,1,2) 'Extract line from line 1 to 2
wscript.echo ExtractLinesFromTextFile(Myfile,2,2) 'Extract line N°2
wscript.echo ExtractLinesFromTextFile(Myfile,1,5) 'Extract line from line 1 to 5
wscript.echo ExtractLinesFromTextFile(Myfile,1,10)'Extract line from line 1 to 10
wscript.echo ExtractLinesFromTextFile(Myfile,8,20)'Extract line from line 8 to 20
wscript.echo ExtractLinesFromTextFile(Myfile,8,40)'Extract line from line 8 to 40
wscript.echo ExtractLinesFromTextFile(Myfile,8,50)'Extract line from line 8 to 50
'*********************************************************************************************************
Public Function ExtractLinesFromTextFile(ByRef TextFile, ByRef FromLine, ByRef ToLine) '<-- Inclusive
    If FromLine <= ToLine Then
        With CreateObject("Scripting.FileSystemObject").OpenTextFile(TextFile)
            Do Until .Line = FromLine Or .AtEndOfStream
                .SkipLine
            Loop
            Do Until .Line > ToLine Or .AtEndOfStream
                ExtractLinesFromTextFile = ExtractLinesFromTextFile & (.ReadLine & vbNewLine)
            Loop
        End With
    Else
        MsgBox "erreur de depassement de lignes", vbCritical, "erreur de depassement de lignes"
    End If
End Function
'*********************************************************************************************************