Question : Import of simple .txt file into MsAccess (2007) Tables - Macro - Automatic

Hi experts,

i'm calling for help on this one.  I have to download data from our database and analyze (now doing it by hand in excel, which has become a "pain in the"), currently i started receiving these files in .txt and they are fixed length delimited.  They could have anywhere from 10 lines to 1000 lines of text.
Attached you will find a sample file.  They always have header data and in between pages more header data.

I need to import: every line that has a delivery note number (they start with 00000......).  Everything else should be left behind.  In my sample file this would represent the import of 52 Lines.  I also only need a few of the columns, but for now I would be quite happy if i could import the complete line and then clean up inside access.

Do you have sample code to do this, that you could share/explain?  The code should import the file (or I import the file manually and then the code cleans the table?) I don't know what the best approach is to this problem.

The column widhts will always have the length as in the sample file....

Appreciate any help!

Answer : Import of simple .txt file into MsAccess (2007) Tables - Macro - Automatic

I moved things around a bit. Also the error is likely because your table column / field is not the right data type for what is being stuffed into it.

Private Sub Import_Click()
    Dim SQL, strCriteria, strMsg, strType As String
    Dim rsTmpI As DAO.Recordset
    Dim ts, arrLine, fso
 'Empty the temp import table
    DoCmd.SetWarnings False
    SQL = "DELETE FROM tblTempImport"
    DoCmd.RunSQL SQL
    Set rsTmpI = CurrentDb.OpenRecordset("tblTempImport", dbOpenDynaset)
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.OpenTextFile("E:\Test.txt", 1)           'Open for Reading
 
    While Not ts.AtEndOfStream
      ' Here is where we get rid of extra spaces and put in a single pipe
      ' Read in the next line, split it at the pipe delimiter
      strReplacedText = ts.Readline
      ' Is it a line with good data? If so, grab it
      If Left(strReplacedText, 5)="00000" Then
         strReplacedText = Replace(strReplacedText, "  ", "|")
         Do While InStr(strReplacedText, "||")
            strReplacedText = Replace(strReplacedText, "||", "|")
         Loop
         ' Now strReplacedText has the data in the format we want
         arrLine = Split(strReplacedText, "|")
         rsTmpI.AddNew
         For i = 0 To UBound(arrLine)
            rsTmpI.Fields(i).Value = arrLine(i)
         Next i
         rsTmpI.Update
      End If
   Wend
   ts.Close

' No need to check for your criteria, we only kept the good lines
rsTmpI.MoveFirst
Do Until rsTmpI.EOF

   'Now do what you want with this record
   rsTmpI.MoveNext
Loop

Done_Import:
    rsTmpI.Close
    Set rsTmpI = Nothing
    DoCmd.SetWarnings True
End Sub
Random Solutions  
 
programming4us programming4us