New to programming, SQL and VBA. I frequently work with decent size data tables and thought it would be helpful to add SQL query execution capability to apply to an existing excel table. Research led me to ADODB connections and found a great base snippet to work from here: https://blog.learningtree.com/excel-as-a-database-how-to-query-economic-data-with-sql/
I seem to running into limits though on how many rows are accessible before the next line of code runs. In my SQL statement source I can return 65k rows, any more in defining the source table size, and I get an Object does not exist error. Can you run ADODB recordset.Open asynchronously to ensure complete return of the object? - Any help would be very much appreciated.
Thanks!
tried to insert a WAIT inline:
rs.Open strSQL, Application.Wait (Now + TimeValue("0:00:30")), cn
but still errors out. See code below
Sub ExcelTbl_SQL()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
strFile = ThisWorkbook.FullName
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open strCon
strSQL = "SELECT * FROM [Sheet1$A1:AI146103] WHERE GROUP = 'HIX'"
rs.Open strSQL, cn
Dim ws As Worksheet
Set ws = Application.Sheets.Add
ws.Range("A1").CopyFromRecordset rs
rs.Close
cn.Close
'Debug.Print rs.GetString
End Sub
These are the results I am getting:
Works: strSQL = "SELECT * FROM [Sheet1$A1:AI65000] WHERE GROUP = 'HIX'"
Error: strSQL = "SELECT * FROM [Sheet1$A1:AI65437] WHERE GROUP = 'HIX'"
Run-time error '-2147217865 (80040e37)': The Microsoft Access database
engine could not find the object 'Sheet1$A1:AI65437'.
I think this is because you are calling old version library through this part of connection string:
Provider=Microsoft.ACE.OLEDB.12.0
You should try
Provider=Microsoft.ACE.OLEDB.16.0
Upd: Answer was here Excel as database - query more than 65536 rows? interesting. You cannot mention rows, or you'll get error.
Related
I have a number of Excel-Files that contain data which I need to combine into one table.
Is it possible and reasonable to do this from within Access VBA code, which I would prefer? Or should I just do it in Excel VBA?
My idea was to iterate through the Excel-Files and use an SQL statement for UPDATE Column WHERE MyCondition, to get the Values I want to the Column I want. Is it possible this way or what would be a suggestion to solving this?
I have tried it this way until now from Access:
Sub Execute_UpdateQuery()
Dim conn As ADODB.Connection
Dim NumOfRec As Integer
Dim strPath As String
strPath = "D:\Sortierliste August_September\Test.xlsx"
Set conn = New ADODB.Connection
conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strPath & ";Extended Properties=Excel 12.0 Xml;HDR=YES;"
conn.Execute "UPDATE Ware SET Name = 'test'" & _
" WHERE Name = 'Ackermann'", NumOfRec, adExecuteNoRecords
Debug.Print NumOfRec & " records were updated."
conn.Close
Set conn = Nothing
End Sub
But that results into an error "Cannot find access-database module "Ware". I guess it is because it is just an excel-table and not a database? I thought it can find an excel-file containing the table called Ware and execute an sql query. Any help or suggestions would be great on how to solve this issue.
Greetz
I've made the following ADODB object declarations in code.
Dim OConn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim fld As ADODB.Field
Set OConn = New ADODB.Connection
Set rs = New ADODB.Recordset
I would like to use the following code to read from a table on a MS Access database file and generate a recordset, rs.
'Get the table name from the search results.
tableName = ThisWorkbook.Sheets("PLC Module Data").Cells(2, 9).Value
'Set the SQL string.
strSql = "SELECT Code, Points, Type, Description, Rating " & _
"FROM " & tableName
'Set the connection string and open the connection to the Access DB.
OConn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=Q:\AutoCAD Improvements\PLC IO Utility Docs\PLC IO Spreadsheet
App\PLC IO App\ace_plc.mdb"
OConn.Open
'Open the recordset and error out if nothing is returned
Set rs = OConn.Execute(strSql)
If rs.EOF Then
MsgBox "No matching records found."
rs.Close
OConn.Close
Exit Sub
End If
I've checked the query statement within the Access file itself and it works fine. I always get the error
Run-time error'-2147217900 (80040e14)': Automation Error
on the line,
Set rs = OConn.Execute(strSql)
If anyone could take a look over my code and determine why this is happening it would be much appreciated. I've looked at similar examples online and it seems like this should be correct.
I added the brackets around the tableName string and it works now. Thanks for all the feedback.
'Set the SQL string.
strSql = "SELECT Code, Points, Type, Description, Rating " & _
"FROM [" & tableName & "]"
This is my first question so constructive criticism is welcome! I am attempting to query an access database from excel vba and place the return information into an Excel range. I get this error:
Error Message: "Run-time error '3709' The connection cannot be used to
perform this operation. It is either closed or invalid in this
context."
Code:
Sub Importfromaccess()
Path = "C:\Users\myUser\Desktop\Database1.accdb"
Set cn = CreateObject("ADODB.connection")
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & Path & ";"
Set rs1 = CreateObject("ADODB.recordset")
rs1.activeconnection = cn
Dim strSQL As New ADODB.Command
strSQL.CommandText = "SELECT * FROM Tooling WHERE TID=BD0001"
strSQL.CommandType = adCmdText
Set rs1 = strSQL.Execute ' This is the line the error occurs on
Sheets("Calc").Range("K1").CopyFromRecordset rs1
End Sub
I have enabled the following references:
Visual Basic For Applications,
Microsoft Excel 16.0 Object Library,
OLE Automation,
Microsoft Office 16.0 Object Library,
Microsoft Access 16.0 Object Library,
Microsoft ActiveX Data Objects 2.0 Library,
I tried placing the line:
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & Path & ";"
right before the error line and received this error:
Run-time error '3705': Operation is not allowed when the object is
open.
Anybody know what my problem might be?
First (and unrelated to your error), unless you need to support clients using Windows 2000 or earlier, you should reference the highest Microsoft ActiveX Data Objects version instead of 2.0. If you're only using ADODB to interact with the database, you don't need the Microsoft Access 16.0 Object Library at all.
Second, if you already have a reference, don't create late bound objects like this:
Set cn = CreateObject("ADODB.connection")
Adding the reference early binds the type, so explicitly declare them and instantiate them using New:
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
Your connection string should be fine - where you run into problems are these 2 lines:
Set rs1 = CreateObject("ADODB.recordset")
rs1.activeconnection = cn
Executing an ADODB.Command will return the Recordset, not the other way around. Remove those 2 lines entirely. Instead of attaching the connection to the Recordset, you need to use it when you're building your ADODB.Command:
Dim strSQL As New ADODB.Command
strSQL.ActiveConnection = cn '<---Insert this.
strSQL.CommandText = "SELECT * FROM Table1"
strSQL.CommandType = adCmdText
Also, get rid of the Hungarian notation there - it's confusing as hell. An ADODB command isn't a String, so why should it be named strFoo?
You also need to clean up after yourself - don't leave your recordset and connection just hanging open when you're done with them. Call .Close when you're finished.
Finally, your SQL statement is most likely incorrect - you probably need to enclose your TID in single quotes('):
"SELECT * FROM Tooling WHERE TID='BD0001'"
It should look closer to this:
Sub Importfromaccess()
Dim Path As String
Path = "C:\Users\myUser\Desktop\Database1.accdb"
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & Path & ";"
Dim query As New ADODB.Command
query.ActiveConnection = cn
query.CommandText = "SELECT * FROM Tooling WHERE TID='BD0001'"
query.CommandType = adCmdText
Dim rs1 As ADODB.Recordset
Set rs1 = query.Execute ' This is the line the error occurs on
Sheets("Calc").Range("K1").CopyFromRecordset rs1
'CLEAN UP AFTER YOURSELF:
rs1.Close
cn.Close
End Sub
You already Set rs1
How about trying something more like:
Sub Importfromaccess()
Dim strSQL As String, strPath as String
Dim cn as Object, rs1 as Object
strPath = "C:\Users\myUser\Desktop\Database1.accdb"
Set cn = CreateObject("ADODB.connection")
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & Path & ";"
Set rs1 = CreateObject("ADODB.Recordset")
strSQL = "SELECT * FROM Tooling WHERE TID='BD0001'"
rs1.Open strSQL, cn
Sheets("Calc").Range("K1").CopyFromRecordset rs1
End Sub
After some thorough rearranging I think I figured it out. I'm surprised at what changes fixed the problem but the following code works:
Dim con As New ADODB.Connection
Dim rs As ADODB.Recordset
Dim cmd As New ADODB.Command
cmd.CommandText = "SELECT * FROM Tooling WHERE TID='BD0001'"
con.Open "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Users\myUser\Desktop\Database1.accdb;"
cmd.ActiveConnection = con
Set rs = cmd.Execute
Sheets("Calc").Range("K1").CopyFromRecordset rs
rs.Close
con.Close
The final error was fixed with:
cmd.CommandText = "SELECT * FROM Tooling WHERE TID='BD0001'"
this line previously did not include single quotes around BD0001.
I also added an ActiveConnection to the Command object.
Edit: This is the simplest working version of this I could manage courtesy of all you helpful people!
I have to create excel macro which fetches from access database and update appropriate columns in excel worksheet.
I have never done VBA programming before, i am just able to write a code to connect to the database which is giving me error saying "Error in From clause".
Sub Button2_Click()
Dim conn As New Connection
Dim rs As New Recordset
strcon = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Users\Xprts8\Documents\shipping.accdb;" & _
"User Id=admin;Password="
conn.Open (strcon)
qry = "SELECT * FROM shipping-table"
rs.Open qry, conn, adOpenKeyset
rs.Close
conn.Close
End Sub
can anybody help me with the following problem
shipping-table is not a valid table name in an SQL statement (because of the hyphen) unless its escaped thusly:
SELECT * FROM [shipping-table]
I have to check whether the connection between Excel and DB2 has been established using CLI/ODBC driver or not.
For that I plan to write a batch file where I will be calling the excel sheet which in turn will automatically execute a macro which will bring out some dummy data from the sysibm.sysdummy1 table.
I require code with which I can make a connection to my database and check if the connection has been established or not by giving out some success message if the connection was established and a failure message if the connection was not established. (Probably with some explanation where the problem occurred)
You can make an ODBC (or OleDB) connection between a DB2 server and Excel using ADODB (ActiveX Data Objects). See this link for sample connection strings.
This link will show you sample VBA code to use with ADODB to connect to your database:
How To Use ADO with Excel Data from Visual Basic or VBA
EDIT: Here's some quick and dirty sample code. Replace the .connectionstring = portion with the proper connection string for your setup.
Dim cn As ADODB.Connection
Dim rs As New ADODB.Recordset
Dim strSQL As String
strSQL = "SELECT * FROM sysibm.sysdummy1 FETCH FIRST 10 ROWS ONLY"
Set cn = New ADODB.Connection
With cn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source=" & App.Path & _
"\ExcelSrc.xls;Extended Properties=Excel 8.0;"
.Open
End With
rs.Open strSQL, cn
rs.MoveFirst
Do Until rs.EOF
Debug.Print rs.Fields(0)
rs.MoveNext
Loop
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing