I'm using the following code to export information from an excel file to an access database. It worked fine last time I used it but ever since I started it up today I've been running into the following issue.
Public Sub Export_to_ACCDB()
Set cn = CreateObject("ADODB.Connection")
dbPath = Application.ActiveWorkbook.Path & "\Newdatabase.accdb"
dbWb = Application.ActiveWorkbook.FullName
dbWs = Application.Worksheets("DATABASE").Name
scn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath
dsh = "[" & Application.ActiveSheet.Name & "$]"
cn.Open scn
'ssql = "INSERT INTO Database ([Column1],[Column2],[Column3]) "
ssql = ssql & "SELECT * FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh
cn.Execute ssql '<<< The error occurs here
End Sub
I get the following error running this code:
Run-time error '-2147217900 (80040e14)':
The INSERT INTO statement contains the following unknown field name: 'F12'. Make sure you have typed the name correctly, and try the operation again.
I don't have a field name called 'F12' in either my excel file or my access database. I can't seem to figure out what's going on.
Column headers are written correctly.
Column headers do not contain spaces or other irregularities.
EDIT:
Seems like Excel thinks you got a 12th column (maybe by accidentally entering something). Mark column L and delete it #FunThomas
This seemed to be the problem. I had to delete all the columns after the last one which contained the correct fieldname. Now it's working again.
Related
I am writing a small application in Excel 2002 and I need to store numbers in some format, it can be a string.
The tables I have a 1:1 relationship and other table is just a table of one column so using access is not necesary and having to have another file is something I'd like to avoid.
So, I want to store it in separate sheets.
However, I like the benefits of SQL for querying and I need it.
I tried using some ADODB connection strings to reach this but I cannot achieve it.
I used the following code:
Dim cn As Object, rs As Object, output As String, sql As String
'---Connecting to the Data Source---
Set cn = CreateObject("ADODB.Connection")
With cn
.Provider = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\MyExcel.xls;"
.ConnectionString = "Data Source=" & ThisWorkbook.FullName & ";" & "Excel 8.0;HDR=Yes;IMEX=1"
.Open
End With
Also, do I have to use ODBC or should I use OLE DB? I don't know if OLE DB could be used to query in excel files.
Also, is it possible to do inserts with SQL using this ODBC or OlE DB?
I tried different providers in the connection string, and I checked the ADO references to be available.
Also, I get this error:
"Error 3706. The specified provider could not be found. It may not be installed properly."
Connection issue
First, there was an error in your Provider string, it should not contain the part with Data Source=C:\MyExcel.xls; since this is part of the connection string. So it should look like this:
.Provider = "Provider=Microsoft.Jet.OLEDB.4.0;"
.ConnectionString = "Data Source=" & ThisWorkbook.FullName & ";" & "Excel 8.0;HDR=Yes;IMEX=1"
ODBC vs OLEDB
I've never used ODBC, but based on this answer, you can't use it to query an Excel file, so OLEDB is the way to go.
Insert Statement
Once you have a working ADODB connection, insert query should work as hoped. I'm providing an example below that worked for me, but there is a few caveats:
I'm using the ACE.OLEDB.12.0 instead of JET.OLEDB.4.0 with Excel for Microsoft 365 MSO (Version 2112 Build 16.0.14706.20000) 64-bit on Windows 10.
I'd suggest to set Mode=ReadWrite in your connection string to avoid potential writting permission issues (but it might work even without it.).
Regarding the IMEX setting, I was having errors when it was set to IMEX=1, so I switched to IMEX=0 (see related question.
The example
With a workbook named Data.xls with the first sheet named Data and the following data :
Data for copy-paste
I can run the following:
Dim wb As Workbook
Set wb = Workbooks("Data.xls")
Dim ws As Worksheet
Set ws = wb.Worksheets("Data")
'Create connection
Dim conn As Object
Set conn = CreateObject("ADODB.Connection")
With conn
.Provider = "Microsoft.ACE.OLEDB.12.0;"
.ConnectionString = "Data Source=" & wb.FullName & ";" & "Excel 8.0;HDR=Yes;IMEX=0;Mode=ReadWrite;"
.Open
End With
'Compose the INSERT statement.
Dim query As String
Const sep = ", "
query = "INSERT INTO [" & ws.Name & "$] " & _
"(Id, Name, Age) " & _
" VALUES (" & _
4 & sep & _
"'" & "Joe" & "'" & sep & _
40 & _
")"
'Execute the statement.
conn.Execute query, adCmdText
'Close the connection
conn.Close
And it should insert the data as follow:
Should you use ACE or JET?
If JET works for you, you might as well use it. Based on this article , you should also have the 32-bit version of ACE available with Windows 7 to work with Excel 2002 (32-bit), but based on your comment it seems like it's causing some problems.
See also some interesting answer about JET vs ACE.
OK. I'm sorry for wasting everyone's time. Like a DUMMY i didn't think simple solution first. The amount of data i am dealing with isn't too large and will actually work better just exporting to an excel file (i'm pretty sure). I would like to thank all that helped (June7, Parfait, and HansUp). The support you guys (everyone on this forum) give has made my job easier by far.
I'm trying to export an Excel Table from my active excel file to an Access database file.
I was getting an error at
"con.excecute sql"
"Run-time error '-2147467259 (80004005)': [Microsoft][ODBC Microsoft Access Driver] Query input must contain at least one table or query."
Sub updateAccess()
Dim con As New ADODB.Connection
Dim connectionString As String
Dim sql, newTable As String
Filename = "C:\Desktop\Quote-Size_Contacts.accdb"
connectionString = "Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" & Filename
con.Open connectionString
' Save current table ("ContactsTbl_Data") to another table ("ContactsTbl_Data_yyyymmdd_hh_mmss")
newTable = "Quote-Size_Contacts_" & Format(Date, "yyyymmdd") & "_" & Format(Now, "hhmmss")
sql = "SELECT CODE, STORE INTO " & newTable & "FROM ContactsTbl_Data"
con.Execute sql
' Delete rows of current table ("ContactsTbl_Data")
sql = "DELETE FROM ContactsTbl_Data"
con.Execute sql
' Insert new rows into current table ("ContactsTbl_Data") from my Excel Sheet
sql = "INSERT INTO ContactsTbl_Data ([CODE], [STORE]) " & _
"SELECT * FROM [Excel 8.0;HDR=YES;DATABASE=" & ThisWorkbook.FullName & "].[" & ThisWorkbook.Sheets("Sheet2").Name & "$]"
con.Execute sql
con.Close
Set con = Nothing
End Sub
EDIT::
I'm not sure standard protocol for these forums on cleaning up the code and asking more questions so i'll just put an "Edit" here.
I applied the suggestions and matched the fields it was trying to save to my access file. I now get the error: "Method 'Execute' of object '_Connection' failed"
Public Sub updateAccess()
Dim con As New ADODB.Connection
Dim connectionString As String
Dim sql, newTable As String
Filename = "C:\Desktop\Quote-Size_Contacts.accdb"
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source='" & Filename & "'"
con.Open connectionString
' Save current table ("ContactsTbl_Data") to another table ("ContactsTbl_Data_yyyymmdd_hh_mmss")
newTable = "Quote-Size_Contacts_" & Format(Date, "yyyymmdd") & "_" & Format(Now, "hhmmss")
sql = "SELECT Company, Contact, Initials, Position, Address, AddressContd, CityStatePost, MainNo, CellNo, FaxNo, Email INTO [" & newTable & "] FROM ContactsTbl_Data"
con.Execute sql
' Delete rows of current table ("ContactsTbl_Data")
sql = "DELETE FROM ContactsTbl_Data"
con.Execute sql
' Insert new rows into current table ("ContactsTbl_Data") from my Excel Sheet
sql = "INSERT INTO ContactsTbl_Data ([Company], [Contact], [Initials], [Position], [Address], [AddressContd], [CityStatePost], [MainNo], [CellNo], [FaxNo], [Email]) " & _
"SELECT * FROM [Excel 12.0 Xml;HDR=Yes;Database=" & ThisWorkbook.FullName & "].[" & ThisWorkbook.Sheets("Sheet2").Name & "$]"
con.Execute sql
con.Close
Set con = Nothing
End Sub
See if this helps.
Table name has hyphen (-) character so use [ ] characters to delimit. Add a space in front of FROM so text doesn't run together in compiled SQL string.
sql = "SELECT CODE, STORE INTO [" & newTable & "] FROM ContactsTbl_Data"
As for connection to Access database, don't think I've ever used or seen Driver, I use Provider:
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source='" & Filename & "'"
Just to give you background of my work, i have to fetch data from MS Sql on daily basis and for that every time have to go to other server to run the query. Once the query is executed, have to paste into my common drive, which takes a lot time. ~55 mins to paste 5,00,000 row & 30 fields to common or to move file. In total 2 hours for execution & movement from one location to other.
To reduce this i would need your help to use the SQL queries through excel with the below things:
If possible,
Point1: Query will be stored in the text file in the common location
Point2: Query Parameter to be populate to get
Or
Point2:Range to be defined for parameter
If not possible above,
Query will be pasted into the code and parameter to be populated based on the above mentioned suggestion.
Connection type is windows authentication, it will work based on logged in users windows name.
This code will allow you to provide variables that you use within your SQL statement and put those into cells on a spreadsheet (In this case Cred2) and return the results on a separate sheet (Sheet2).
The first portion of the code establishes a connection with the SQL server.
The column Headers will be started in Row 2 and then the data will begin populating starting on row 3. I have used this to pull well over 100,000 records at a time and this works very quickly.
Private Sub CommandButton1_Click()
Dim cn As Object
Dim rs As Object
Dim strCon As String
Dim strSQL As String
strCon = "DRIVER=SQL Server;SERVER=ServerName;DATABASE=DBName;Trusted_Connection=True"
Set cn = CreateObject("ADODB.Connection")
cn.Open strCon
' if not a trusted connection you could replace top line of strCon with
strCon = "DRIVER=SQL Server; Server=myServerAddress;Database=myDataBase;User Id=myUsername; Password=myPassword"
' set up where you are getting your variables to include in the SQL statement
stat = Sheets("Cred2").Range("c7").Value
barg = Sheets("Cred2").Range("c10").Value
worksite = Sheets("Cred2").Range("c11").Value
' Construct SQL statement
strSQL = "select * " _
& " FROM tableName A , table2 B " _
& "WHERE A.[field1] = B.[field1] " _
& " and field1 like '" & stat & "'" _
& "and field2 like '" & barg & "'" _
& "and field3 like '" & worksite & "'" _
& " order by Field? "
' Build Record Set
Set rs = CreateObject("ADODB.RECORDSET")
rs.ActiveConnection = cn
rs.Open strSQL
' Display Data
For intColIndex = 0 To rs.Fields.Count - 1
Sheet2.Range("A2").Offset(0, intColIndex).Value = rs.Fields(intColIndex).name
Next
Sheet2.Range("A3").CopyFromRecordset rs
' Close Database
rs.Close
cn.Close
Set cn = Nothing
end sub
So I currently have this code
Public Sub DoTrans()
Set cn = CreateObject("ADODB.Connection")
dbPath = Application.ActiveWorkbook.Path & "\db1.accdb"
dbWb = Application.ActiveWorkbook.FullName
dbWs = Application.ActiveSheet.Name
scn = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & dbPath
dsh = "[" & Application.ActiveSheet.Name & "$]" & "namedrange1"
cn.Open scn
ssql = "INSERT INTO Table1 ([fdName], [fdOne], [fdTwo]) "
ssql = ssql & "SELECT * FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh
cn.Execute ssql
End Sub
But this inserts into existing Access table. I'd like to be able to modify this to create linked tables, based on a list of named ranges that I have in Excel so that all the named ranges will be converted to tables in Access. Formatting is not an issue as I know the format of the ranges that are named are OK to be used as tables in Access.
Is there a way to easily do this?
INSERT INTO appends to existing tables, SELECT .... INTO creates new ones.
If you want to rewrite that query to a SELECT INTO, it would be as simple as this:
ssql = "SELECT * INTO Table1 "
ssql = ssql & "FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh
Note that you first need to delete the table if you want to overwrite it.
Your question has several subquestions. I can get into creating links in ADO on specific columns, but you haven't shown an attempt, nor have you shared enough information to write an applicable answer.
A sample to elaborate on the TransferSpreadsheet method :
Dim sNT as String, sWB as String, sRN as String sNT = "Table1" sWB = "C:\MyWorkBook.xls" sRN = "namedrange1" DoCmd.TransferSpreadSheet acLink, , sNT, sWB, True, sRN
This has to be run in a module in ms-access.
I would like to have a simple tool built using excel vba to update existing records and also to add new records to an access database. The goal is to use only 2 clicks to complete the action.
First Part - Resolved (Retrieve Data from Access Database): I have created a excel table that queries data from access database in a tab named "Mapping Matrix" , so everytime an update is required, will use a function to refresh the data.
So, I will update the existing data in the Sheet "Mapping Matrix", or even add new data before I will require this data to be propagated into my access database.
Second Part - Please help (Update the access database "Mapping" using the excel spreadsheet tab "Mapping Matrix")
Here is what I have done to try update existing records with that queried in Excel. However I am faced with this error message that says "The INSERT INTO statement contains the following unknown field name: 'F1'. Make sure you have typed the name correctly, and try the operation again."
Do not quite understand how to fix the error, as I have not applied F1 in the code.
Note: I will require this data to replace that in the access database (not adding on to existing data)
Thanks all in advance!
Public Sub Populate_Data()
Set cn = CreateObject("ADODB.Connection")
dbPath = "Access Database Path.mdb"
dbWb = Application.ActiveWorkbook.FullName
dbWs = Application.ActiveSheet.Name
scn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & dbPath
dsh = "[" & Application.ActiveSheet.Name & "$]"
cn.Open scn
ssql = "INSERT INTO Mapping ([Field1], [Field2], [Field3]) "
ssql = ssql & "SELECT * FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh
cn.Execute ssql
End Sub