I needed a way to automatically import a user selected Excel spreadsheet into a new (dynamic) Access table.

I will move it to the code bank if there is no glaring error

This was what I came up with. It is fast, very fast, compared to other methods of looping past each Excel cell etc.

It also creates and formats the new Table dynamically – no matter how many columns exist in the Excel sheet.

I also needed a way to return the success of the Function, being one of three states. So I decided to return a tri-state using a Long. The calling routine can then display the status (in a StatusBar) what happened. Ie. Import Successful, User Selected Cancel (from the CommonDialog Show Open) or an unsuccessful import.

Note: It was written for VBA (as a Module).

VB Code:
  1. 'In a Module
  2. Option Compare Database
  3. Option Explicit
  4.  
  5. Public Function Import_SpreedSheet() As Long
  6. Dim cnnExcel As ADODB.Connection
  7. Dim rstExcel As ADODB.Recordset
  8. Dim strSQLExcel As String
  9. Dim strSQL As String
  10. Dim strExcelToOpen As String
  11. Dim strSheetName As String
  12. Dim intFieldCount As Integer
  13. Dim intIdx As Integer
  14. Dim strColBuff As String
  15.  
  16. On Error GoTo Err_Handler
  17.  
  18.     'Obtain the Excel File to be used for the Import
  19.     strExcelToOpen = Open_Dialog(Application.hWndAccessApp)
  20.     If strExcelToOpen = "" Then
  21.         Import_SpreedSheet = 1
  22.         Exit Function 'As Cancel was pressed
  23.     End If
  24.  
  25.     Set cnnExcel = New ADODB.Connection
  26.     Set rstExcel = New ADODB.Recordset
  27.  
  28.     cnnExcel = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strExcelToOpen & ";Extended Properties=""Excel 8.0;HDR=No"""
  29.     cnnExcel.Open
  30.  
  31.     'Capture the First Sheet name. This is used to as the Table Save Name
  32.     strSheetName = cnnExcel.OpenSchema(adSchemaTables).Fields("TABLE_NAME").Value
  33.  
  34.     strSQLExcel = "SELECT * FROM [" & strSheetName & "]"
  35.     rstExcel.Open strSQLExcel, cnnExcel
  36.  
  37.     If Not (rstExcel.BOF Or rstExcel.EOF) Then
  38.  
  39.         'Capture the number of Fields required
  40.         intFieldCount = rstExcel.Fields.Count - 1   '0 based
  41.  
  42.         'Create the dynamic Fields Names base on the number of Columns
  43.         For intIdx = 0 To intFieldCount
  44.             If intIdx < intFieldCount Then
  45.                 strColBuff = strColBuff & rstExcel.Fields(intIdx).Name & " varchar, "
  46.             Else
  47.                 strColBuff = strColBuff & rstExcel.Fields(intIdx).Name & " varchar"
  48.             End If
  49.         Next
  50.  
  51.         'Now we have used the 'Sheet' name, it's time to strip of the ADO parenthesis (being ' & $)
  52.         strSheetName = Replace(Replace(strSheetName, "'", ""), "$", "")
  53.  
  54.         'Add a new (unique) Table
  55.         strSQL = "CREATE TABLE [tbl" & strSheetName & "] (" & strColBuff & ")"
  56.         CurrentProject.Connection.Execute strSQL
  57.  
  58.         'Now the Table has been corectly formated, add the SpreedSheet data
  59.         DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, "tbl" & strSheetName, strExcelToOpen, False, "A:" & Chr$(64 + intFieldCount + 1)
  60.  
  61.     End If
  62.  
  63.     'Perform Housekeeping (as required)
  64.     If rstExcel.State = adStateOpen Then
  65.         rstExcel.Close
  66.         Set rstExcel = Nothing
  67.     End If
  68.     If cnnExcel.State = adStateOpen Then
  69.         cnnExcel.Close
  70.         Set cnnExcel = Nothing
  71.     End If
  72.  
  73.     Import_SpreedSheet = True
  74.  
  75. Exit Function
  76.  
  77. Err_Handler:
  78.  
  79.     If Err.Number = -2147217900 Then    'Table already exists
  80.          MsgBox "Please change the Excel WorkSheet Name," & vbCrLf & _
  81.          "as this becomes the Save Name of the Table.", vbOKOnly + vbInformation, "Table Already Exists!"
  82.     Else
  83.          MsgBox "Description: " & Err.Description & vbCrLf & _
  84.         "Number: " & Err.Number, vbOKOnly + vbInformation, "Import Error!"
  85.     End If
  86.  
  87.     'Destroy objects (as required)
  88.     If rstExcel.State = adStateOpen Then
  89.         rstExcel.Close
  90.         Set rstExcel = Nothing
  91.     End If
  92.     If cnnExcel.State = adStateOpen Then
  93.         cnnExcel.Close
  94.         Set cnnExcel = Nothing
  95.     End If
  96.  
  97.     Import_SpreedSheet = False
  98.  
  99. End Function

My calling routine:
VB Code:
  1. 'On my Form
  2.     Me.sbMain.Panels(1).Text = "Importing"
  3.  
  4.     Select Case Import_SpreedSheet 'Call the Function, return result
  5.         Case True   'Success
  6.             Me.sbMain.Panels(1).Text = "Complete"
  7.             MsgBox "Excel SpreedSheet sucessfully imported.", vbOKOnly + vbInformation, "Complete"
  8.             Me.sbMain.Panels(1).Text = "Ready"
  9.         Case False  'An error occured
  10.             Me.sbMain.Panels(1).Text = "Error"
  11.         Case 1      'Cancel was pressed
  12.             Me.sbMain.Panels(1).Text = "Canceled"
  13.     End Select