I have this code that imports a csv file into an Access table.
There are several problems or ideas that are beyond my level of skills.
The first issue is the file does not append existing fields, instead the entire file is inserted create a duplicate including new headers.
The second issue is I would like to export only new or updated records in a csv file out of Access, not the entire table, I have not gotten there yet.
I need a little hand holding here.
Thank you everyone, this forum and you guys are the best. Always helpful and wailing to share your knowledge.
Option Compare Database
Option Explicit
Private Sub ImportFile()
Dim strPathFile As String, strFile As String, strPath As String
Dim strTable As String
Dim xlApp As Object, xlWb As Object, xlWs As Object
Dim lngRow As Long, lngLastRow As Long
Dim rst As DAO.Recordset
strPath = "C:\Transit\"
strTable = "Transit"
strFile = Dir(strPath & "*.csv")
Set rst = CurrentDb.OpenRecordset(strTable)
Do While Len(strFile) > 0
strPathFile = strPath & strFile
Set xlApp = CreateObject("Excel.Application")
Set xlWb = xlApp.Workbooks.Open(strPathFile)
Set xlWs = xlWb.Worksheets(1)
lngLastRow = xlWs.UsedRange.Rows.Count
For lngRow = 1 To lngLastRow
rst.AddNew
rst("Field1") = xlWs.Range("A" & lngRow).Value
rst("Field2") = xlWs.Range("B" & lngRow).Value
rst("Field3") = xlWs.Range("C" & lngRow).Value
rst("Field4") = xlWs.Range("D" & lngRow).Value
rst("Field5") = xlWs.Range("E" & lngRow).Value
rst("Field6") = xlWs.Range("F" & lngRow).Value
rst("Field7") = xlWs.Range("G" & lngRow).Value
rst.Update
Next
xlApp.Quit
Set xlApp = Nothing
Set xlWb = Nothing
Set xlWs = Nothing
strFile = Dir()
Loop
rst.Close
Set rst = Nothing
End Sub
I would suggest creating a linked table to that file. Once you’ve done that, you can treat the linked Excel file like any other table, including running SELECT and action queries. In your case, you could create a simple Append query with the Excel spreadsheet as its destination, and limit it to only those records which haven’t been updated.
It will also be visible in the Query Designer’s Add Tables dialog box.
Updated
If the path to the Excel file is not fixed, you will need a little VBA to automate relinking the file.