Public Function ImportData2800()
Const IMPORT_FOLDER As String = "C:\Shared\Reports\Data\"
Dim dbsCurrent As DAO.Database
Dim fldField As DAO.Field
Dim intFile As Integer
Dim lngField As Long
Dim strFields() As String
Dim strFile As String
Dim strLine As String
Dim strTable As String
Dim strDevice As String
Dim strValues() As String
Dim rstImportData As DAO.Recordset
Dim tdfTableDef As DAO.TableDef
' Process files
Set dbsCurrent = CurrentDb
strFile = Dir(IMPORT_FOLDER & "\*.txt")
Do Until strFile = ""
' Open file
intFile = FreeFile
Open IMPORT_FOLDER & strFile For Input Access Read Shared As #intFile
' Name the master table here
strTable = "TBL_DATA" 'Change me to whatever you want
' Name the device
strDevice = Left(strFile, Len(strFile) - 4)
' Read column headings
If Not EOF(intFile) Then
Line Input #intFile, strLine
strFields = Split(strLine, vbTab)
End If
' This should get rid of any double spaces.
For j = 0 To UBound(strFields)
strFields(j) = Replace(strFields(j), " ", " ")
Next
' Add the column for the device into our list of columns
ReDim Preserve strFields(0 To UBound(strFields) + 1) As String
strFields(UBound(strFields)) = "Device"
' Create table, if necessary
Set tdfTableDef = Nothing
On Error Resume Next ' Ignore missing table
Set tdfTableDef = dbsCurrent.TableDefs(strTable)
On Error GoTo 0
If tdfTableDef Is Nothing Then
Set tdfTableDef = dbsCurrent.CreateTableDef(strTable)
End If
' Create fields, if necessary
For lngField = 0 To UBound(strFields)
Set fldField = Nothing
On Error Resume Next ' Ignore missing fields
Set fldField = tdfTableDef.Fields(strFields(lngField))
On Error GoTo 0
If fldField Is Nothing Then
Set fldField = tdfTableDef.CreateField(strFields(lngField), dbText) ' Always create text fields
tdfTableDef.Fields.Append fldField
End If
Next
' Create date stamp date field, if necessary
Set fldField = Nothing
On Error Resume Next ' Ignore missing field
Set fldField = tdfTableDef.Fields("DateStamp")
On Error GoTo 0
If fldField Is Nothing Then ' No DateStamp field
Set fldField = tdfTableDef.CreateField("DateStamp", dbDate)
fldField.DefaultValue = "Date()"
tdfTableDef.Fields.Append fldField
End If
On Error Resume Next ' Ignore existing table
dbsCurrent.TableDefs.Append tdfTableDef
On Error GoTo 0
' Read file
Set rstImportData = CurrentDb.OpenRecordset(strTable)
Do Until EOF(intFile)
Line Input #intFile, strLine
strValues = Split(strLine, vbTab)
ReDim Preserve strValues(0 To UBound(strValues) + 1) As String
strValues(UBound(strValues)) = strDevice
' Import data
rstImportData.AddNew
For lngField = 0 To UBound(strValues)
rstImportData(strFields(lngField)) = strValues(lngField)
Next
rstImportData.Update
Loop
rstImportData.Close
' Close file
Close #intFile
strFile = Dir
Loop
End Function
|