VBA如何使用StreamReader跳过一行

时间:2016-08-01 10:12:58

标签: vba excel-vba streamreader excel

在VBA中,我必须比较文本文件的两个版本并打印不匹配的行。但是,如果已将更多(用户指定的)行添加到更新的文本文件中,则必须忽略此行,并且必须继续比较更新文本文件中的下一行。文本文件非常大,我不能使用ReadAll属性。 到目前为止,我假设每个文本文件中的行数相同且顺序保持不变,因此我只使用第一个文本文件循环遍历所有行。

Dim JsonPrev, JsonCurr As String  'Names of the text files
Dim strLinePrev , strLineCurr As String  'The file text
Dim UserLineAdded As String

LineAdded = MsgBox("Does the most recent JSON contain an additional input / output, which the first does not?", vbYesNo, "Alert!")

    If LineAdded <> vbNo Then
        UserLineAdded = InputBox("Please provide the line that was added" & vbNewLine & "E.g. INPUT AdjustToDate, or OUTPUT Surrender Charge Base")
        If UserLineAdded = vbNullString Then
            MsgBox ("Comparison cancelled.")
            Exit Sub
        End If
    End If

JsonPrev = Range("JSONPrevious").Value  'First Text File name
JsonCurr = Range("JSONCurrent").Value   'Second Text File name

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFilePrev = objFSO.OpenTextFile(JsonPrev, 1)
Set objFileCurr = objFSO.OpenTextFile(JsonCurr, 1)

DiffCount = 0

Do Until objFilePrev.AtEndOfStream
    strLinePrev = objFilePrev.ReadLine
    StrLineCurr = objFileCurr.ReadLine

    prevLineNumber = prevLineNumber + 1
    currLineNumber = currLineNumber + 1
    If prevLineNumber > 0 Or currLineNumber > 0 Then
        'Check whether a Line was added
        If InStr(1, UCase(StrLineCurr), UCase(UserLineAdded)) Then
            currLineNumber = currLineNumber + 1
            '*****Add code to update StrLineCurr to the next ReadLine*****
        End If

        If strLinePrev <> StrLineCurr Then
                DiffCount = DiffCount + 1
                'code to print both lines from different sources
            End If
        End If
    End If

Loop

objFilePrev.Close
objFileCurr.Close

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

如果在第一个文件中找到(用户指定的)行,我假设您还需要忽略第二个文件中的相应行。

修改你的代码

Do Until objFilePrev.AtEndOfStream
  strLinePrev = objFilePrev.ReadLine
  StrLineCurr = objFileCurr.ReadLine

  prevLineNumber = prevLineNumber + 1
  currLineNumber = currLineNumber + 1
 '''''''''''''''''
 ' add the next line , and define the function user_specified

 if user_specified(strLinePrev) then Continue While   ' ignore it

....

 loop
  ....

  ''''''''''''''''''''''''''''''''''''
function user_specified(line as string) As Boolean
 ' define the logic of user specified string
  ' return True ?false

end function