Results 1 to 4 of 4

Thread: Auto Import WorkSheet into a dynamic Access Table - Example

  1. #1

    Thread Starter
    INXSIVE Bruce Fox's Avatar
    Join Date
    Sep 2001
    Location
    Melbourne, Australia
    Posts
    7,429

    Auto Import WorkSheet into a dynamic Access Table - Example

    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

  2. #2

    Thread Starter
    INXSIVE Bruce Fox's Avatar
    Join Date
    Sep 2001
    Location
    Melbourne, Australia
    Posts
    7,429

    Re: Auto Import WorkSheet into a dynamic Access Table - Example

    Here is the CommonDialog Module (addapted from AllApi.net)
    VB Code:
    1. Option Compare Database
    2. Option Explicit
    3.  
    4. Declare Function GetOpenFileName Lib "comdlg32.dll" Alias "GetOpenFileNameA" (pOpenfilename As OPENFILENAME) As Long
    5.  
    6. Private Type OPENFILENAME
    7.     lStructSize As Long
    8.     hwndOwner As Long
    9.     hInstance As Long
    10.     lpstrFilter As String
    11.     lpstrCustomFilter As String
    12.     nMaxCustFilter As Long
    13.     nFilterIndex As Long
    14.     lpstrFile As String
    15.     nMaxFile As Long
    16.     lpstrFileTitle As String
    17.     nMaxFileTitle As Long
    18.     lpstrInitialDir As String
    19.     lpstrTitle As String
    20.     flags As Long
    21.     nFileOffset As Integer
    22.     nFileExtension As Integer
    23.     lpstrDefExt As String
    24.     lCustData As Long
    25.     lpfnHook As Long
    26.     lpTemplateName As String
    27. End Type
    28.  
    29. Public Function Open_Dialog(ByVal lngHwnd As Long) As String
    30.     Dim OFName As OPENFILENAME
    31.     OFName.lStructSize = Len(OFName)
    32.     'Set the parent window
    33.     OFName.hwndOwner = lngHwnd
    34.     'Set the application's instance
    35.     ''''OFName.hInstance =
    36.     'Select a filter
    37.     OFName.lpstrFilter = "Excel Files (*.xls)" & vbNullChar & "*.xls" & vbNullChar
    38.     'Create a buffer for the file
    39.     OFName.lpstrFile = Space$(254)
    40.     'Set the maximum length of a returned file
    41.     OFName.nMaxFile = 255
    42.     'Create a buffer for the file title
    43.     OFName.lpstrFileTitle = Space$(254)
    44.     'Set the maximum length of a returned file title
    45.     OFName.nMaxFileTitle = 255
    46.     'Set the initial directory
    47.     OFName.lpstrInitialDir = CurrentProject.Path
    48.     'Set the title
    49.     OFName.lpstrTitle = "Select an Excel WorkSheet to Import"
    50.     'No flags
    51.     OFName.flags = 0
    52.  
    53.     'Show the 'Open FileDialog
    54.     If GetOpenFileName(OFName) Then
    55.         Open_Dialog = Replace(Trim$(OFName.lpstrFile), Chr(0), "")
    56.     Else
    57.         Open_Dialog = ""
    58.     End If
    59. End Function

  3. #3
    Ex-Super Mod RobDog888's Avatar
    Join Date
    Apr 2001
    Location
    LA, Calif. Raiders #1 AKA:Gangsta Yoda™
    Posts
    60,709

    Re: Auto Import WorkSheet into a dynamic Access Table - Example

    We sure do think alike. I just finished with a thread in the db forum on similar Excel mechanics.

    Access and Excel

    Great job on using all ADO to provide the solution. I used a combo of ADO and Excel Object Model.
    VB/Office Guru™ (AKA: Gangsta Yoda®)
    I dont answer coding questions via PM. Please post a thread in the appropriate forum.

    Microsoft MVP 2006-2011
    Office Development FAQ (C#, VB.NET, VB 6, VBA)
    Senior Jedi Software Engineer MCP (VB 6 & .NET), BSEE, CET
    If a post has helped you then Please Rate it!
    Reps & Rating PostsVS.NET on Vista Multiple .NET Framework Versions Office Primary Interop AssembliesVB/Office Guru™ Word SpellChecker™.NETVB/Office Guru™ Word SpellChecker™ VB6VB.NET Attributes Ex.Outlook Global Address ListAPI Viewer utility.NET API Viewer Utility
    System: Intel i7 6850K, Geforce GTX1060, Samsung M.2 1 TB & SATA 500 GB, 32 GBs DDR4 3300 Quad Channel RAM, 2 Viewsonic 24" LCDs, Windows 10, Office 2016, VS 2019, VB6 SP6

  4. #4

    Thread Starter
    INXSIVE Bruce Fox's Avatar
    Join Date
    Sep 2001
    Location
    Melbourne, Australia
    Posts
    7,429

    Re: Auto Import WorkSheet into a dynamic Access Table - Example

    Hi RD

    It was the dynamic table that spawned this method - there was nothing that I could find that could do what I needed...

    Cheers,
    Last edited by Bruce Fox; Oct 18th, 2005 at 06:08 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width