Public Function ImportFixedWidthTextFile(TextPath As String, TextFileName As String, TableName As String)
'*************************************************************************************************************************
'Created by :D Crake X-Craft Limited
'Date :30th June 2009
'Arguments :TextPath - folder where the incoming text file is located
' :TextFileName - name of file in above folder
' :TableName - name of table that text file is being import into
'
'Purpose :Open up a fixed width text file and by reading the schema from a table it imports the relevant data
' :into the relevant fields in the table.
' :
'Comments :Table name in col 1, fieldname in col 2, start pos in col 3, field length in col 4
'Example :ImportFixedWidthTextFile("C:\Temp","TextFile.txt","TblSampleData")
'Issues :Does not validate the existance of the table or that the field are named correctly
'**************************************************************************************************************************
'Copywrite :There is no copywrite on this code, however, if passed on then pass on the above comments.
'**************************************************************************************************************************
'Does the source file exist in the target folder?
If Dir(TextPath & "\" & TextFileName) = "" Then
MsgBox "Path or file name is invalid", vbExclamation + vbOKOnly, "Import Abandoned"
Exit Function
End If
Dim Rs As DAO.Recordset
Dim Rs2 As DAO.Recordset
Dim strFieldName As String
Dim sPos As Integer
Dim sLen As Integer
Dim strText As String
Set Rs = CurrentDb.OpenRecordset("Select * From tblSchemas Where fldTblName = '" & TableName & "'")
Set Rs2 = CurrentDb.OpenRecordset(TableName)
If Not Rs.EOF And Not Rs.BOF Then
'read the contents of the text file one line at a time
Open TextPath & "\" & TextFileName For Input As #1
Do Until EOF(1)
Line Input #1, strText
'Get the table defnintions from the table
Do Until Rs.EOF
strFieldName = Rs(1)
sPos = Rs(2)
sLen = Rs(3)
'add the portion of the string to the record in the table
Rs2.AddNew
Rs2(strFieldName) = Mid(strText, sPos, sLen)
Rs2.Update
Rs.MoveNext
Loop
Loop
Rs.Close
Close #1
End If
'close the instances of the objects
Set Rs = Nothing
Set Rs2 = Nothing
End Function