将2行文本流写入一个Access记录

问题描述 投票:0回答:2

我有以下代码,如果找到值(N1),它会读取文本文件并写入Access表

    Do While Not objStream.AtEndOfStream
        strLine = objStream.ReadLine
        ReDim MyArray(0)
        MyArray = Split(strLine, ",")
        If MyArray(0)= "N1" Then
            rs.AddNew
            rs("Field1") = MyArray(0)
            rs("Field2") = MyArray(1)
            rs.Update
        End If
    Loop

我想知道在写入数据库之前是否可以检查文本流的下一行以及是否找到值N2,然后将其写入记录

所以,如果我的示例文本文件数据是......

N1 Cat
N2 Cat
N1 Dog
N1 Fish
N2 Fish
N1 Hamster
N2 Hamster

...我对Access的预期输出将是: -

Field 1 Field 2 Field 3 Field 4
N1      Cat     N2      Cat
N1      Dog
N1      Fish    N2      Fish
N1      Hamster N2      Hamster

我查找了textstream对象,找不到读取下一行的方法。

vba ms-access access-vba
2个回答
1
投票

这应该是你需要的:

如有必要,缓冲区用于存储预读行。

'Definition of the buffer
Dim buffer As String
'Now also check if the buffer is filled
Do While (Not objStream.AtEndOfStream) Or (Len(buffer) > 0)
    'If the buffer is filled, use and clear it, instead read next line 
    If Len(buffer) > 0 Then
        strLine = buffer
        buffer = vbNullString
    Else
        strLine = objStream.ReadLine
    End If
    ReDim MyArray(0)
    MyArray = Split(strLine, ",")
    If MyArray(0)= "N1" Then
        rs.AddNew
        rs("Field1") = MyArray(0)
        rs("Field2") = MyArray(1)
        'Read a line to the buffer and check if it starts with 'N2'
        buffer = objStream.ReadLine
        If buffer Like "N2*" Then
            'Use the content of the buffer, store it in Field3 and 4, and clear it
            MyArray = Split(buffer, ",")
            buffer = vbNullString
            rs("Field3") = MyArray(0)
            rs("Field4") = MyArray(1)
        End If
        rs.Update
    End If
Loop

0
投票

你可以试试这样的东西,不确定它是不是最好的方法。

Sub c()

Dim f As Scripting.FileSystemObject
Dim t As Scripting.TextStream
Dim a() As String
Dim n1() As String
Dim n2() As String
Dim l As Long
Dim rs As Object

Set f = New Scripting.FileSystemObject
Set t = f.OpenTextFile("C:\Workspace\Dummy Data\dummy.txt", ForReading)

a = Split(t.ReadAll, vbCrLf)

t.Close

For l = 0 To UBound(a)

    n1 = Split(a(l), " ")

    If n1(0) = "N1" Then

        rs.addnew
        rs("Field1") = n1(0)
        rs("Field2") = n1(1)

        If l + 1 < UBound(a) Then
            n2 = Split(a(l + 1), " ")
            If n2(0) = "N2" Then
                rs("Field3") = n2(0)
                rs("Field4") = n2(1)
            End If
            l = l + 1
        End If

        rs.Update
        Erase n1
        Erase n2

    End If

Next l

erase a


End Sub
© www.soinside.com 2019 - 2024. All rights reserved.