Results 1 to 10 of 10
  1. #1
    jo15765's Avatar
    jo15765 is offline Expert
    Windows 10 Access 2016
    Join Date
    Nov 2010
    Location
    6 Feet Under
    Posts
    672

    VBA Import CSV Into Table

    I am importing a csv into an access table. In Excel Column D, the value could be 111111 or could be 111111-000, if the value is hyphenated, I want to split on the hyphen and everything to the left of the hyphen goes in table field name GymIdNum, and everything to the right of the hyphen goes in GymIdVar, then Column E would be the next field name of the database table


    Code:
    
    For i = 2 To xlWorksheet.UsedRange.Rows.Count
        row = xlWorksheet.Rows(i).Value
        rs.AddNew
        For j = 1 To 17
            If j = 4 And InStr(1, row(1, j), "-") > 0 Then
                Dim parts() As String
                parts = Split(row(1, j), "-")
                rs.Fields(j - 1).Value = parts(0)
                rs.Fields(j).Value = parts(1)
                j = j + 1
            ElseIf j < 4 Then
                rs.Fields(j - 1).Value = row(1, j)
            Else
                rs.Fields(j).Value = CStr(row(1, j - 1))
            End If
        Next j
        rs.Update
    Next i

  2. #2
    June7's Avatar
    June7 is offline VIP
    Windows 10 Access 2010 32bit
    Join Date
    May 2011
    Location
    The Great Land
    Posts
    52,929
    So, what is the issue? Does code work? Error message, wrong result, nothing happens?
    How to attach file: http://www.accessforums.net/showthread.php?t=70301 To provide db: copy, remove confidential data, run compact & repair, zip w/Windows Compression.

  3. #3
    ranman256's Avatar
    ranman256 is offline VIP
    Windows Vista Access 2010 32bit
    Join Date
    Apr 2014
    Location
    Kentucky
    Posts
    9,525
    normally you dont import text files 1 record at a time


    '*******************
    ' TEXT FILE IMPORT
    '*******************

    attach the text file as an external table,
    then make an append query(s) to import the columns and data you wish.
    the query will correct errors in the data


    text files require a SPEC file to define the columns so there's some pre-steps to take:

    ---------------
    PREP
    ---------------
    1st, manually import the text file,
    in the 'import screen' ,bottom left corner is ADVANCED
    define your fields in the text as an IMPORT SPEC.
    SAVE this spec. (i.e: "SpecName")


    manually link this CSV file using the spec name so it becomes an External Table: txtFile2Import

    make an append query to append the txtFile2Import fields to the target table: qaImportCsvFile


    ---------------
    EXECUTION
    ---------------
    1. each new CSV file you get, save it to the same place every time,like: c:\temp\txtFile2Import.csv
    2. run the import query(s): docmd.openquery "qaImportCsvFile"
    3. Done

  4. #4
    jo15765's Avatar
    jo15765 is offline Expert
    Windows 10 Access 2016
    Join Date
    Nov 2010
    Location
    6 Feet Under
    Posts
    672
    No it is not working for me....what I am doing is first creating the table in vba
    Code:
    Sub CreateStagingTable()
        Dim db As Database
        Dim tbl As TableDef
        Dim fld As Field
        Set db = CurrentDb
        
        Set tbl = db.CreateTableDef("ABCD_Temp")
        tbl.Fields.Append tbl.CreateField("Location", dbText, 255)
        tbl.Fields.Append tbl.CreateField("CreatedBy", dbText, 255)
        tbl.Fields.Append tbl.CreateField("ResNum", dbText, 255)
        tbl.Fields.Append tbl.CreateField("CNum", dbText, 255)
        tbl.Fields.Append tbl.CreateField("VNum", dbText, 255)
        tbl.Fields.Append tbl.CreateField("SNum", dbText, 255)
        tbl.Fields.Append tbl.CreateField("ST", dbText, 255)
        tbl.Fields.Append tbl.CreateField("AN", dbText, 255)
        tbl.Fields.Append tbl.CreateField("Name", dbText, 255)
        tbl.Fields.Append tbl.CreateField("Address", dbText, 255)
        tbl.Fields.Append tbl.CreateField("City", dbText, 255)
        tbl.Fields.Append tbl.CreateField("St", dbText, 255)
        tbl.Fields.Append tbl.CreateField("Zip", dbText, 255)
        tbl.Fields.Append tbl.CreateField("Phone", dbText, 255)
        tbl.Fields.Append tbl.CreateField("RDA", dbCurrency)
        tbl.Fields.Append tbl.CreateField("SDA", dbCurrency)
        tbl.Fields.Append tbl.CreateField("TID", dbCurrency)
        tbl.Fields.Append tbl.CreateField("Green", dbText, 255)
        tbl.Fields.Append tbl.CreateField("CD", dbText, 255)
        
        db.TableDefs.Append tbl
        db.Close
        Set fld = Nothing
        Set tbl = Nothing
        Set db = Nothing
        
        MsgBox "Table created successfully.", vbInformation
    End Sub
    Then trying to import the file with vba....it was working until the requirement to split on the hyphen into two diff columns
    Code:
    Private Sub ImportSelectedFile(filePath)
    Dim db As Database
    Dim tbl As TableDef
    Dim rs As Recordset
    Dim row As Variant
    Dim i As Integer
    Dim j As Integer
    
    
    Set db = CurrentDb
    Set tbl = db.TableDefs("ABCD_Temp")
    Set rs = tbl.OpenRecordset
    
    
    Dim xlApp As Object
    Dim xlWorkbook As Object
    Dim xlWorksheet As Object
    Set xlApp = CreateObject("Excel.Application")
    Set xlWorkbook = xlApp.Workbooks.Open(filePath)
    Set xlWorksheet = xlWorkbook.Sheets(1)
    
    
    For i = 2 To xlWorksheet.UsedRange.Rows.Count
        row = xlWorksheet.Rows(i).Value
        rs.AddNew
        For j = 1 To 17
            If j = 4 And InStr(1, row(1, j), "-") > 0 Then
                Dim parts() As String
                parts = Split(row(1, j), "-")
                rs.Fields(j - 1).Value = parts(0)
                rs.Fields(j).Value = parts(1)
                j = j + 1
            ElseIf j < 4 Then
                rs.Fields(j - 1).Value = row(1, j)
            Else
                rs.Fields(j).Value = CStr(row(1, j - 1))
            End If
        Next j
        rs.Update
    Next i
    
    
    xlWorkbook.Close False
    xlApp.Quit
    Set xlWorksheet = Nothing
    Set xlWorkbook = Nothing
    Set xlApp = Nothing
    rs.Close
    db.Close
    Set rs = Nothing
    Set tbl = Nothing
    Set db = Nothing
    
    
    MsgBox "Data imported successfully.", vbInformation
    
    
    
    
    
    
    End Sub

    I have a button on a form, where the user selects the file

  5. #5
    Join Date
    Jan 2017
    Location
    Swansea,South Wales,UK
    Posts
    4,940
    So use an intermediate table for the import.?
    Split the hyphenated field when you move from that table to your real table.

    Not sure creating a table all the time is great for bloating the DB?
    Please use # icon on toolbar when posting code snippets.
    Cross Posting: https://www.excelguru.ca/content.php?184
    Debugging Access: https://www.youtube.com/results?sear...bug+access+vba

  6. #6
    jo15765's Avatar
    jo15765 is offline Expert
    Windows 10 Access 2016
    Join Date
    Nov 2010
    Location
    6 Feet Under
    Posts
    672
    I'm not sure what you are suggesting?

    Using a temp table for the import so the user can validate the data before importing into the actual production table

  7. #7
    Join Date
    Jan 2017
    Location
    Swansea,South Wales,UK
    Posts
    4,940
    No, You bring the data into a temp table and then split that field, then transfer the data you require to your real table.
    That, or just split as you display.

    I'm against storing that and the split data as well. One or the other.
    Please use # icon on toolbar when posting code snippets.
    Cross Posting: https://www.excelguru.ca/content.php?184
    Debugging Access: https://www.youtube.com/results?sear...bug+access+vba

  8. #8
    jo15765's Avatar
    jo15765 is offline Expert
    Windows 10 Access 2016
    Join Date
    Nov 2010
    Location
    6 Feet Under
    Posts
    672
    ah so I see - split it in acess instead of trying to in the import.

    Okay - any thoughts on how to better the import process? Someone said below row/by/row was a bad idea.

  9. #9
    Join Date
    Jan 2017
    Location
    Swansea,South Wales,UK
    Posts
    4,940
    https://learn.microsoft.com/en-us/of...d.transfertext

    Do it manually once and create a specification if needed.
    Please use # icon on toolbar when posting code snippets.
    Cross Posting: https://www.excelguru.ca/content.php?184
    Debugging Access: https://www.youtube.com/results?sear...bug+access+vba

  10. #10
    CJ_London is online now VIP
    Windows 10 Access 2010 32bit
    Join Date
    Mar 2015
    Posts
    11,430
    I use sql to import text files.

    two basic constructs

    Code:
    SELECT *
    FROM (SELECT * FROM [sheet1$A:E] AS xlData IN 'C:\Path\xlName.XLSX'[Excel 12.0;HDR=no;IMEX=0;ACCDB=Yes])  AS XL;
    and

    Code:
    SELECT *
    FROM [excel 12.0 xml;hdr=yes;imex=1;DATABASE=C:\Path\xlName.XLSX].[Sheet1$] AS T;
    I prefer the first method because you can easily apply access functionality to modify the values as required. e.g.

    the value could be 111111 or could be 111111-000, if the value is hyphenated, I want to split on the hyphen and everything to the left of the hyphen goes in table field name GymIdNum, and everything to the right of the hyphen goes in GymIdVar
    Code:
    SELECT  fld1, fld2, fld3, iif(instr(fld4,"-")>0,left(fld4,instr(fld4,"-")-1,fld4) AS GymIdNum, iif(instr(fld4,"-")>0,mid(fld4,instr(fld4,"-")+1,"") AS GymIdVar, fld5.....etc


    Get your select working as required, then convert the query to an append or make table as required

Please reply to this thread with any new information or opinions.

Similar Threads

  1. Replies: 9
    Last Post: 09-22-2022, 03:12 AM
  2. Export Filtered table to Excel, Edit and Re-Import Changes to Access Table
    By Access_throwaway in forum Import/Export Data
    Replies: 15
    Last Post: 02-20-2018, 12:37 PM
  3. Replies: 13
    Last Post: 01-25-2016, 01:36 PM
  4. import table to append to a table in Access 2010
    By Stephanie53 in forum Forms
    Replies: 2
    Last Post: 05-23-2013, 03:40 PM
  5. Replies: 7
    Last Post: 04-15-2011, 08:46 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Other Forums: Microsoft Office Forums