Link to home
Start Free TrialLog in
Avatar of ranhell
ranhellFlag for Mexico

asked on

Visual Basic 6 read TXT file and store it in different fields again

have the following Test.txt file content
field1   field2      field3
1           1           0035300608E000233004
1           2           0035160508E000012950
2           3           0035210508E000017574

Separated by a blank space each and CR at the end

I need to read this file from an specific folder "Say C:\TEST\Test.txt" or Optionally browse for the TXT file and store each field in Access 2003 using DAO Recordset


Any written code or sample code is very much appreaciated
Avatar of Robberbaron (robr)
Robberbaron (robr)
Flag of Australia image

1/ how do you want the file selected ?  CommonDialog ?

2/ do you need to use a recordset as i find SQL easier.



Option Explicit
Sub GetData(sInputFile)
    Dim ffn As Long, sTemp As String, sData() As Variant
    Dim cnData As New ADODB.Connection, iRa As Integer
    
    'open the connection to the database....
    cnData.Open connstring, usrid, pwd
    
    ffn = FreeFile
    Open sInputFile For Input As #ffn
    Do While Not EOF(ffn)
        Line Input #ffn, sTemp
        sData = Split(sTemp, " ", , vbTextCompare)
        
        sSQl = "INSERT INTO mytable"
        sSQl = sSQl & " ( Field1 , Field2 , Field3 ) "
        sSQl = sSQl & " VALUES( " & sData(0) & ", " & sData(1) & ", " & sData(2) & ")"
        cnData.Execute sSQl, iRa
        
        If iRa <> 1 Then
            MsgBox "Error on insert"
        End If
    Loop
        
    Close #ffn
 
End Sub

Open in new window

Avatar of ranhell

ASKER

What is the difference between this code below and the one you provided.

dim fso as object 'scripting.filesystemobject
set fso = createobject("scripting.filesystemobject") ' = new scripting.filesystemobject
dim fReader as object 'scripting.TextStream
set fReader = fso.OpenTextStream("C:\TEST\Test.txt") 'optional second argument is ForReading...

dim strLine as string
dim arrfields() as string
while not fReader.AtEndOfStream
  strLine = fReader.ReadLine
  arrFields = split(strLine, " ")
  'here, you can insert the data into the records... I do assume you know how to do that?

wend
freader.Close
set freader = nothing
set fso = nothing
ASKER CERTIFIED SOLUTION
Avatar of Robberbaron (robr)
Robberbaron (robr)
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial