我有以下代码,如果发现值(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对象,却找不到读取下一行的方法。
答案 0 :(得分: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
答案 1 :(得分: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