readline

S

SAC

I have a text file with each field on a line. A record consists of seven
lines and then there's a new record.

How can I load this into a table. A little code snipet would be wonderful.

Thanks.
 
N

Nikos Yannacopoulos

Try the following:

Sub import_text_file()
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim vFile As String
Dim vTable As String
Dim vLine
Dim i As Integer

vFile = "C:\SomeFolder\SomeFile.txt"
vTable = "TargetTableName"

Set db = CurrentDb()
Set rst = db.OpenRecordset(vTable)

Open vFile For Input As #1

On Error GoTo EndOfFile
Do Until EOF(1)
rst.AddNew
For i = 0 To 6
Line Input #1, vLine
rst.Fields(i) = vLine
Next
rst.Update
Loop

EndOfFile:
Close #1
Set rst = Nothing
Set db = Nothing
End Sub

Note: this assumes you have already created the target table, and the fields
are in the same sequence as in the source text file.
You will also need to add an appropriate DAO reference, if not already
there. Appropriate is DAO 3.51 for A97, DAO 3.6 for A2K or later. To add the
reference, while in the VB window go Tools > References, check the already
selected ones on top, and if you don't have it scroll down looking for
Microsoft DAO 3.XX Object Library. Check it and click OK.
Remember to change the source file and target table names assigned to VFile
and vTable to the actual ones.

HTH,
Nikos
 
S

SAC

Excellent! Thanks

Nikos Yannacopoulos said:
Try the following:

Sub import_text_file()
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim vFile As String
Dim vTable As String
Dim vLine
Dim i As Integer

vFile = "C:\SomeFolder\SomeFile.txt"
vTable = "TargetTableName"

Set db = CurrentDb()
Set rst = db.OpenRecordset(vTable)

Open vFile For Input As #1

On Error GoTo EndOfFile
Do Until EOF(1)
rst.AddNew
For i = 0 To 6
Line Input #1, vLine
rst.Fields(i) = vLine
Next
rst.Update
Loop

EndOfFile:
Close #1
Set rst = Nothing
Set db = Nothing
End Sub

Note: this assumes you have already created the target table, and the fields
are in the same sequence as in the source text file.
You will also need to add an appropriate DAO reference, if not already
there. Appropriate is DAO 3.51 for A97, DAO 3.6 for A2K or later. To add the
reference, while in the VB window go Tools > References, check the already
selected ones on top, and if you don't have it scroll down looking for
Microsoft DAO 3.XX Object Library. Check it and click OK.
Remember to change the source file and target table names assigned to VFile
and vTable to the actual ones.

HTH,
Nikos
 
Top