比较基于行号VB2008的文本文件的内容

时间:2013-03-20 09:40:03

标签: vba

我们说我有两个文本文件,我会比较(基于文本的行编号 - >见下文),因为这是生成唯一键的位置。

sample1.txt:

5th line -> _000_000F_01CE2577.B840E640

sample2.txt

5th line -> _000_000F_01CE2577.B840E640

现在这是我的代码:

            Dim FILE_NAME As String = "C:\myfiles"

            'This is to determine the number of lines in the text file
            Dim count As Integer
            count = 0

            Dim obj As StreamReader
            obj = New StreamReader(FILE_NAME)

            Do Until obj.ReadLine Is Nothing
                count = count + 1
            Loop

            '------------------------------
            'this is my computation to get the number of line -->disregard this

            Dim temp3 As Integer
            temp3 = count - 3
            '------------------------------

            obj.Close()

            'This is to read all the text in the text file
            Dim fileReader(fs) As String
            fileReader(fs) = My.Computer.FileSystem.ReadAllText(FILE_NAME, _
                        System.Text.Encoding.ASCII)

我已将每个文件存储在一个数组中 例如:

             file[0]
             file[1]

然后我必须阅读每个文件及其内容,现在我将如何比较文本行。我相信我必须使用正则表达式。

请给我一些关于如何比较文字行的指示...

e.g。 sample1.txt中的第5行== sample2.txt的第5行

我必须知道它们是否相同。

1 个答案:

答案 0 :(得分:1)

这应该为你做的工作 它将读取txt文件中的每一行,将其保存到数组然后比较
注意: 设置路径执行2个txt文件
如果文件2中的行少于文件1,它将超出范围。虽然可以添加一些代码来处理这种情况。

Option Explicit

Sub Read_text_File()

    Dim firstFile() As String, secondFile() As String
    Dim path1 As String, path2 As String
    Dim i As Long

    path1 = "C:\ ... .txt"
    path2 = "C:\ ... .txt"

    Call fill_array(firstFile, path1)
    Call fill_array(secondFile, path2)

    For i = LBound(firstFile) To UBound(firstFile) - 1
        Debug.Print (firstFile(i) & vbTab & vbTab & vbTab & vbTab & secondFile(i))
        If StrComp(firstFile(i), secondFile(i), vbTextCompare) = 0 Then
            MsgBox "Line: " & i + 1 & "  matches "
        End If
    Next i

End Sub

Sub fill_array(ByRef arr() As String, pathToFile As String)

    Dim oFSO As New FileSystemObject
    Dim oFS As TextStream

    Dim cnt As Long
    cnt = 0

    Set oFS = oFSO.OpenTextFile(pathToFile)

    Do Until oFS.AtEndOfStream
        oFS.ReadLine
        cnt = cnt + 1
    Loop
    ReDim arr(cnt)
    Set oFS = oFSO.OpenTextFile(pathToFile)
    cnt = 0
    Do Until oFS.AtEndOfStream
        arr(cnt) = oFS.ReadLine
        cnt = cnt + 1
    Loop

    oFS.Close
    Set oFS = Nothing
End Sub