Search code examples
loopsvbscript

VBS Looping returning NEXT line then expected


I am trying to find a field value in a flat file, and set a variable based on that value. Here is my code:

Set file = fso.OpenTextFile(DataFileName, 1)
do until file.AtEndOfStream
    if StrComp(left(file.readLine, 3) , "H23") = 0 Then
        WScript.Echo file.ReadLine
        If StrComp(Split(file.readLine, "~")(4) , "1") = 0 Then
            ExportMapName = "ExportMap_1"
        Else
            ExportMapName = "ExportMap_2"
        End If

    End If
loop
Wscript.Echo ExportMapName

However, when it gives me the ReadLine value, it shows H24 like, it skips right over the H23 line. I'm sure I have my loops nested incorrectly, but I'm not able to find any where that gives me guidance. TIA!


Solution

  • Calling ReadLine on the TextStream object returned by OpenTextFile advances the reader to the next line. A simplified illustration of your issue:

    do until file.AtEndOfStream
        WScript.Echo file.ReadLine 'returns a line
        WScript.Echo file.ReadLine 'returns the next line
    loop
    

    Also notice the logic error: if the first ReadLine is the last line in the file, an error will occur on the second ReadLine.