Option Compare Database
Option Explicit
Dim fieldName As String, fieldLen As Integer
Function ImportFromFile(FileName As String)
Dim db As DAO.Database, rst As DAO.Recordset
Dim strRecord As String, arrayFields() As String, xCol As Integer, i As Integer, pos As Integer
Dim recSpec() As String, containsData As Boolean
ReDim [COLOR=Red]recSpec(6)
recSpec(0) = "CP01"
recSpec(1) = "FI01"
recSpec(2) = "NM01"
recSpec(3) = "PR01"
recSpec(4) = "SC01"
recSpec(5) = "SH06"
recSpec(6) = "TU4R"[/COLOR]
Set db = CurrentDb
Set rst = db.OpenRecordset("[COLOR=Red]tblImport[/COLOR]")
' Initialise the array to store the fields
ReDim arrayFields(UBound(recSpec))
Open FileName For Input As #1 ' Open the import file.
While Not EOF(1)
Line Input #1, strRecord
If Len(strRecord & "") > 0 Then
' Save each part of the record into the array
For i = 0 To UBound(recSpec)
SetFieldVal recSpec(i)
pos = InStr(1, strRecord, recSpec(i), vbBinaryCompare)
If pos > 0 Then
arrayFields(i) = Mid(strRecord, pos, fieldLen)
containsData = True
End If
Next
' Create new record and insert data if at least one of the fields contain data.
If containsData = True Then
With rst
.AddNew
For xCol = 0 To UBound(recSpec)
If Len(recSpec(xCol) & "") > 0 Then
SetFieldVal recSpec(xCol)
.Fields(fieldName) = arrayFields(xCol)
End If
Next
.Update
End With
containsData = False
End If
End If
Wend
Close #1
rst.Close
Set rst = Nothing
MsgBox "Successfully Imported!"
End Function
[COLOR=Red]Function SetFieldVal(fieldID As String)[/COLOR]
Select Case fieldID
Case "CP01"
'-- Name Field
fieldName = "Field1"
fieldLen = 95
Case "FI01"
'-- Address field
fieldName = "Field2"
fieldLen = 23
Case "NM01"
'-- Shipping Address
fieldName = "Field3"
fieldLen = 70
Case "PR01"
'-- Bankruptcy Info
fieldName = "Field4"
fieldLen = 168
Case "SC01"
'-- Connection Status
fieldName = "Field5"
fieldLen = 34
Case "SH06"
'-- Connection Status
fieldName = "Field6"
fieldLen = 14
Case "TU4R"
'-- Unknown field identity
fieldName = "Field7"
fieldLen = 62
End Select
[COLOR=Red]End Function[/COLOR]