Excel VBA(Tansferring data excel to access table

Hi guys

I am trying to use the below code to transfer the data in to access database. but I am getting an error like
"the INSERT INTO statement contains the following un known field name:'F12'.Make sure you have type the name correctly and try the operation again. I already check the fields name in database and in excel also
 Sub Data_Transfer()

Dim cn As Object
 '//I am using late binding for creating objects, this code will run on any version of Excel
 Set cn = CreateObject("ADODB.Connection")

' //This line will set the path of Ms.Access database, in this case it is assumed that Ms.Access DB will be in same folder as in Excel File.
 dbPath = Application.ActiveWorkbook.Path & "\SDOD.mdb"

' // This line will set the path of Active workbook
 dbWb = Application.ActiveWorkbook.FullName

 '// Get the Active sheet name, so that we can correctly Export data using this variable
 dbWs = Application.ActiveSheet.Name

 '// Set the connection, we are creating Excel workbook connection
 scn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & dbPath

' //Another variable to hold worksheet name, but in this case it will //be in a format that is required to pass in open connection //method, which execute the SQL statement in next line
  dsh = "[" & "Sheet1" & "$]"

 '// Open the connection
 cn.Open scn

 '//Create SQL statement using proper sheet name dsh, created //before opening connection

 ssql = "INSERT INTO Candidate ([Source],[C_Name])"
 ssql = ssql & "SELECT * FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh

 '//Run the SQL
 cn.Execute ssql

 End Sub

Open in new window

Who is Participating?

Improve company productivity with a Business Account.Sign Up

surah79Connect With a Mentor Author Commented:
I have this now working but I have used the below code to get it work, hopefully it will help others. thanks a lot for your help
Public Function insertRecord() As Boolean

Dim SaveTime As Date
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim lItem As Long
Dim listCount As Long
Dim fileTypes() As Variant
Dim docTypeString As String
Dim clipboard       As MSForms.DataObject
Dim i, j As Integer
Dim Lastrow As Integer

On Error GoTo Err:
'dataValidate(sourceField As String, dataEntered As String, Optional sendCompany As Boolean, _
'Optional sendTP As Boolean) As Boolean

For Each Cell In Sheet1.Range("a2:K1000")
    Cell.Value = Trim(Cell.Value)

    Cell.Value = Application.WorksheetFunction.Clean(Cell.Value)

'ReDim fileTypes(1) As Variant


'//Database Location
'Changed so that people with different drive mappings wont have issues

Const DB_LOCATION = "\\au012\Tcsgroup\SCHTORS-\On-bData\BackUp\Test\SDOD.mdb"

    '//Table has a datecreated/datemodified timestamp for each record
    SaveTime = Now
    With ActiveSheet
        Lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
    End With
  i = 2
    '//Open Database
    If db Is Nothing Then
       Set db = DAO.Workspaces(0).OpenDatabase(DB_LOCATION)
    End If
 For j = 1 To Worksheets("Sheet1").Range("O4")
    '//Open Table
    If rs Is Nothing Then
        Set rs = db.OpenRecordset("System Access", dbOpenDynaset)
    End If
    '//Create a new record
    With rs
        ![Brand_Name] = Sheet1.Cells(i, 1).Value
        '//isCompany has been removed. Defaults to false, database does not use.
        ![Staff-Group] = Sheet1.Cells(i, 2).Value
        ![System_Name] = Sheet1.Cells(i, 3).Value
        ![Banker_Name] = Sheet1.Cells(i, 4).Value
       ' ![custPosition] = Sheet1.Cells(2, 1).Value
        ![Batch] = Sheet1.Cells(i, 5).Value
            ![Request_Num] = Sheet1.Cells(i, 6).Value
            ![Request_Date] = Sheet1.Cells(i, 7).Value
            ![ENumber] = Sheet1.Cells(i, 9).Value
             ![MNumber] = Sheet1.Cells(i, 10).Value
             ![Status] = Sheet1.Cells(i, 11).Value
       ' ![docTypes] = docTypeString
       ![request_By] = Sheet1.Cells(i, 8).Value
      '  ![requestTime] = Now
        '//Insert Record into Database
        insertRecord = True '//SUCCESSFUL INSERTION
       i = i + 1

    End With
 Next j
    Set rs = Nothing
    Set db = Nothing
    Exit Function

    Select Case Err.Number
        Case 3024
            MsgBox "Error: Could not establish connection to DB: Could not find file"
            Exit Function
        Case 3008
            MsgBox "Error: Could not establish connection to DB: Opened exclusively"
            Exit Function
        Case -2147221040
            Resume Next
        Case Else
            MsgBox Err.Number & ": " & Err.Description
            Exit Function
    End Select
End Function

Open in new window

Ryan ChongCommented:
>>"the INSERT INTO statement contains the following un known field name:'F12'.Make sure you have type the name correctly and try the operation again
can you provide us sample files of your Excel and Access db?

from that error, you may rename the field's name and select the correct fields before importing.
surah79Author Commented:
Hi Ryan

Please find attached the database and excel file.

Easily Design & Build Your Next Website

Squarespace’s all-in-one platform gives you everything you need to express yourself creatively online, whether it is with a domain, website, or online store. Get started with your free trial today, and when ready, take 10% off your first purchase with offer code 'EXPERTS'.

Being an Access developer, I would approach this from the Access side and import the Excel data by linking to the workbook and running an append query.

In any event, the problem is most likely caused because the sheet has extraneous columns in it.

If you have ever had additional columns, Excel remembers them unless you delete them correctly.  Simply selecting the columns and pressing the delete key, clears the contents but it does NOT delete the columns. You must select the columns and right -click to select delete.  Same issue occurs with phantom rows.  Since Excel is very flexible as to cell content, it is perfectly happy to have "empty" rows or columns because the data and presentation layers are merged since your sheet is most often laid out as a report rather than a table.
surah79Author Commented:
hi Pat

I am trying to make this excel as user form which will be used to collect/ input data in the access database.
I don't want everyone to go inside and run the append query as this will be a multi user database.

Gustav BrockCIOCommented:
You must specify the two field names to pull data from:
ssql = "INSERT INTO Candidate ([Source],[C_Name]) "
ssql = ssql & "SELECT SomeField, SomeOtherField FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh

Open in new window

I'm not sure why you are using Excel as a FE to Access.  The process would be much simpler if you simply used an Access FE.  If you are worried about licensing, don't.  The Access runtime is free so you can distribute an Access FE to everyone and have it linked to the shared database.  Download the free Access runtime engine from the Microsoft download site.
Ryan ChongCommented:

based on the Excel file provided, you should try this:
ssql = "INSERT INTO [System Access] ([Banker_Name],[Staff-Group],[System_Name],[Request_Num],[Request_Date],[Request_By],[ENumber],[MNumber],[Status],[Batch],[Brand_Name])" & _
       " SELECT [Banker_Name],[Staff-Group] ,[System_Name], [Request_Num], [Request_Date], [Request_By], [Enumber], [Mnumber], [Status], [Batch],[Brand_Name] " & _
       " FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh
 '//Run the SQL
 cn.Execute ssql

Open in new window

surah79Author Commented:
hi Ryan

It is Still giving the same error.

Ryan ChongCommented:

It is Still giving the same error.
it was tested fine in my machine before I posted the scripts.

I have this now working but I have used the below code to get it work, hopefully it will help others. thanks a lot for your help
glad that you resolved the issue using another approach. you may close this question when necessary.
surah79Author Commented:
Didn't work for me
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.