Microsoft Access Insert Into Statement Selecting D

2019-09-09 09:57发布

问题:

I am trying to use an Insert Into query to select data from an Excel file and insert it into an Access table. The issue I'm having is one of the Excel columns can be letters, numbers or both. I would like to select the data as text, but I seem to only get blanks for the text and text/number entries. If I sort the Excel file so that a text item is in the first row, all data is converted. I have tried the following:

strSQL = "INSERT INTO tblImport ([TIMS Company Code]) " & _
    "SELECT [TIMS Company Code] " & _
    "FROM [Excel 8.0;HDR=YES;DATABASE=" & xlPath & "].[Manual Entry$];"

=========================================================================

strSQL = "INSERT INTO tblImport ([TIMS Company Code]) " & _
    "SELECT CStr([TIMS Company Code]) " & _
    "FROM [Excel 8.0;HDR=YES;DATABASE=" & xlPath & "].[Manual Entry$] " & _
    "WHERE [TIMS Company Code] IS NOT NULL;"

=========================================================================

strSQL = "INSERT INTO tblImport ([TIMS Company Code]) " & _
    "SELECT (CAST([TIMS Company Code]) AS TEXT) " & _
    "FROM [Excel 8.0;HDR=YES;DATABASE=" & xlPath & "].[Manual Entry$];"

I have also looked into something called "schema.ini" but it seems a little over my head.

I appreciate any help someone can provide.

Jason

回答1:

As you have found out, Access tries to be helpful, and guess the data type based on the first 8 rows.

There are two workarounds:

  1. Add a dummy row of text at the top - discard that when reading
  2. save the file as CSV, and use a Saved import specification


回答2:

After a lot more research I have learned a lot, but not found a solution. For anyone who stumbles down this road, here are a few things worth knowing:

  • The issue occurs because Access looks at the first 8 rows and makes a decision on data type based on that
  • There are several things you can add to the connection string, but none of them help if the first 8 rows are integer and there are text values later
  • IMEX=1 will work if there is at least 1 row of text in the first 8
  • You can adjust the registry settings to look at more then the first 8, by going here:[HKLM\Software\Microsoft\Jet\4.0\Engines\Excel
  • I wasn't able to find a way to change registry settings from within VBA, but if your working with C#.Net then it is totally possible
  • Most info on this subject is in regards to Microsoft SQL Server, but is still helpful
  • Here is a link to the most useful website I found: https://yoursandmyideas.wordpress.com/2011/02/05/how-to-read-or-write-excel-file-using-ace-oledb-data-provider/