Link to home
Create AccountLog in
Avatar of "Abys" Wallace
"Abys" WallaceFlag for United States of America

asked on

Excel Export to Access

Hi Experts,

I'm using a 32 bit sys and would like to export an Excel table to an Access.accdb database.

I found the following code online:
Option Explicit

Dim objConnection As ADODB.Connection
 
Sub ConnectToDatabase(strDBpath As String)
    Set objConnection = New ADODB.Connection
    objConnection.Open "Microsoft.ACE.OLEDB.12.0; " & _
    "Data Source=" & strDBpath
End Sub
 
Sub ExportToAccess(rngData As Range, Optional blnHeader As Boolean = False)
    Dim rstTable        As ADODB.Recordset
    Dim lngRow          As Long
    Dim lngCol          As Long
    Dim strDB           As String
    Dim strTable        As String
    Dim intStartRow     As Integer
 
    If blnHeader = False Then
        intStartRow = 1
    Else
        intStartRow = 2
    End If
 
'---------------------User Inputs-------------------------------
'Provide database path
    strDB = "E:\DAS Project w Nate\DASProductivity.accdb"
'Provide SQL Query or Table name from database
    strTable = "test"
'===============================================================
    
'Establish Database connection
On Error GoTo ErrH
    Call ConnectToDatabase(strDB)
 
    Set rstTable = New ADODB.Recordset
    rstTable.Open strTable, objConnection, adOpenKeyset, adLockOptimistic, adCmdTable
 
'Check if No of data columns are same as No. of fields in database
    If rngData.Columns.Count <> rstTable.Fields.Count Then
        MsgBox "No. of columns in data is different from no. of fields in DB table", vbCritical, "Export Error"
        GoTo ExitH
    End If
 
    For lngRow = intStartRow To rngData.Rows.Count
        With rstTable
            .AddNew
            For lngCol = 0 To (.Fields.Count - 1)
                .Fields(lngCol) = rngData.Cells(lngRow, lngCol + 1).Value
            Next lngCol
            .update
        End With
    Next lngRow
On Error GoTo 0
    GoTo ExitH
ErrH:
    If objConnection.State = 1 Then rstTable.CancelUpdate
    MsgBox Err.Number & vbCrLf & Err.Description, vbCritical, "Export Error"
ExitH:
    If objConnection.State = 1 Then rstTable.Close
    Set rstTable = Nothing
End Sub
 
Sub CloseDB()
    objConnection.Close
    Set objConnection = Nothing
End Sub

Open in new window


Which errors out from the start at:
ErrH:
    If objConnection.State = 1 Then rstTable.CancelUpdate
    MsgBox Err.Number & vbCrLf & Err.Description, vbCritical, "Export Error"

Open in new window


with the following error:
-2147467259 [Microsoft][ODBC Driver Manager]Data source name not found and no default driver specified

How can I get this to work?  Is it something I need to set up in my reference library?
**skill level novice**

Thanks!  :)
Avatar of GrahamSkan
GrahamSkan
Flag of United Kingdom of Great Britain and Northern Ireland image

You need a reference to the Microsoft Active Data Objects, but if that were missing you would get a different error. What version of Office are you using?
Avatar of "Abys" Wallace

ASKER

@GrahamSkan  I'm using Windows 7 Office 2010
Why not try Importing an Excel Table into Access?

http://en.kioskea.net/faq/8645-importing-an-excel-table-into-access

All you have to do is record the steps above into a VBA Macro in Access and you'll have the code.
Hi shorvath...  Thank you for the alternate method recommendation.

But I wanted to export because I'll have multiple end users that'll export their data at different intervals throughout the day.  I wanted to include a command button on the userform that'll allow them the ability to send it to a table in the database.
It looks to me that the error is in the ConnectToDatabase sub. This line:

    objConnection.Open "Microsoft.ACE.OLEDB.12.0; " & _
    "Data Source=" & strDBpath

Are you sure the database path is correct?
@Fyrsten.. thank you for pointing me in the right direction but the export still isn't functioning.  How do I handle allocating points in this instance... Do I have to start a new question for the new error?

After researching the issue I found that I needed to change the "Provider" line of code to the following...

   
objConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0; " & _
             "Data Source=" & strDBpath 

Open in new window



which now produces the error my database is in an unrecognizable format.  Unrecognized database format 'F:\DASProductivity.mdb'

so I removed that version and created a new database with the following format-  F:\DASProductivity.accdb and I still receive the same error.

would you know why neither format is being recognized?

Kindest Regards
abys757, that error could happen when you create a database in Access2010 using the new features, and then tries to open it in Access2007

Which version of Access did you use to create that database?
The version of Access 2010.
ASKER CERTIFIED SOLUTION
Avatar of shorvath
shorvath
Flag of Canada image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Thank you @shorvath  ....  

I tested the vb code and it gave an object required error at this point in the code:
    DoCmd.TransferSpreadsheet 0, 8, "tblTest", _
           ActiveWorkbook.FullName, True, _
           Replace(Rng.Address, "$", "")

Open in new window


Kind Regards~
see last line of my post

(Note: Make reference to Access 14.0 Obj Lib in Excel)
My apologies .. moving so fast I failed to read your "Note:"...

Thank you.. exactly what I was looking for shorvath!

Appreciate
Tonya
@shorvath ... is there a way to get the code to work on multiple sheets?  I have an excel workbook with 5 sheets each containing a table (List Object) that would need to be sent to 5 different tables in Access.  Is there a way to specify each sheet and which table it should go to?  Link to new question is

New Multi List Obj to Access DB tables

Thanks!  :)
Yes,  the first line sets the Range

Set Rng = ActiveSheet.ListObjects(1).Range

all you have to do is switch the active sheet, select the Range on that sheet and then change the target table name from "tblTest" to the target table of that sheet.
Hi @shorvath.. I attempted your recommendation prior to re-posting and I keep getting field "F1" isn't in my destination table "tblSWAC" ..

I've attached a sample of my set up.  All I did was modify the workbook / sheet name and destination table name.

Also I started a new question with a link to it above your last response.  Would you like to continue within the body of the new question you can respond there.  Just wanted to ensure you get your points for your assistance.   :)

Dim AccDatabase As Object
Dim FilePath As String
Dim Rng As Range

Set Rng = Workbooks("repTemplate_RoamingTracker.xlsm").Worksheets("Swac").ListObjects("SWACTracker").Range

FilePath = "F:\EE Sample VBA_Excel\Test.accdb"
Set AccDatabase = CreateObject("Access.Application")
With AccDatabase
    .Visible = False
    .OpenCurrentDatabase FilePath
    DoEvents
    
    DoCmd.TransferSpreadsheet 0, 8, "tblSwac", _
           ActiveWorkbook.FullName, True, _
           Replace(Rng.Address, "$", "")
    DoEvents
    .Quit
End With

Open in new window

Book1.xlsm
Test.accdb