Weird ODBC error - sql

I'm using an Access front-end for an Microsoft SQL back-end.
The problem I'm facing, is that I'm inserting data with an adodb connection. I use this on multiple forms. On the first form it works, on the second form it works, on the third form it also works. But on the fourth form I get an: 'ODBC: Call failed' error.
You might think I made some kind of typing error, but that is not the issue. When I start with form four I can insert the data.
So long story short, after 3 inserts on different form, I get that odbc error. I don't know what the problem is.
Dim Query As String
Dim rs As ADODB.Recordset
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
Query = "SELECT MAX(ID) From dbo_Controle"
rs.Open Query, CurrentProject.Connection
rs.MoveFirst
ID = rs.Fields(0).Value
Query = "INSERT INTO dbo_Controle VALUES (" & ID + 1 & ",'" & Me.txtControleTime & "')"
Set cn = CurrentProject.Connection
Debug.Print (Query)
cn.Execute Query
rs.Close
cn.Close
Set rs = Nothing
Set db = Nothing
This is the code I am using on different forms with different queries.

I was having the same issue, and was able to fix it by using CurrentProject.AccessConnection

Related

VBA: Querying data in dynamic named range

I create named range that covers data I need to query using ADODB
SourceWB.Names.Add Name:=SOME_RANGE_NAME, RefersTo:=SOME_RANGE
I setup a connection run SQL query
sConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & sSourceName_ & "; Extended Properties=""Excel 12.0 Macro;HDR=YES"";"
Set oConn_ = New ADODB.Connection
oConn_.Open sConn
Dim oRs As New ADODB.Recordset
oRs.Open sSQL, oConn_, adOpenStatic, adLockReadOnly, adCmdText
The SQL query is
SELECT * FROM [SOME_RANGE_NAME] WHERE ....
The problem is: these commands are in cycle, where every time there may be other range referenced by SOME_RANGE_NAME. If the range is changing within one sheet, everything is ok. As soon the SOME_RANGE_NAME references range in other sheet I get the following error:
no value given for one or more required parameters
The solution was proper closing of connections!

How return multi-result (2 tables) from sql-query into Excel Worksheet?

I have sql query which returne 2 tables with different structure as a result.
I nee somehow to wrote code in VBA/VSTO to get this 2 table from that sql-query.
What should i start from?
Is it possible at all?
The short answer is yes, it's possible. You'll need to use code a bit like that below:
Sub ConnectionExample6()
Dim cnn As ADODB.Connection
Dim rs As ADODB.Recordset
Set cnn = New ADODB.Connection
' Open a connection by referencing the ODBC driver.
cnn.ConnectionString = "driver={SQL Server};" & _
"server=MySqlServer;uid=MyUserName;pwd=MyPassword;database=pubs"
cnn.Open
' Create a Recordset by executing an SQL statement.
Set rs = cnn.Execute("Select * From authors")
' Show the first author.
MsgBox rs("au_fname") & " " & rs("au_lname")
' Close the connection.
rs.Close
End Sub
Source is here:
https://msdn.microsoft.com/en-us/library/ms807027.aspx
Try to use this, then come back and tell us if you have problems.

Excel VBA to Execute Stored UNION Query from MS Access 2003

I'm writing a function in Excel VBA to execute a stored queries on a database created using MS Access 2003. The code works when the stored query is a simple query, but NOT if the query is a UNION. For example, I'm using the following code to execute the stored queries:
Public Function QueryDB()
Dim cn As Object
Dim strConnection As String
Set cn = CreateObject("ADODB.Connection")
' Hard code database location and name
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\server1\myDatabase.mdb"
' Open the db connection
cn.Open strConnection
' Create call to stored procedure on access DB
Dim cmd As Object
Set cmd = CreateObject("ADODB.Command")
cmd.CommandType = adCmdStoredProc
cmd.CommandText = "testQuery"
cmd.ActiveConnection = cn
' Execute stored query
Dim rs As ADODB.Recordset
Set rs = cmd.Execute()
MsgBox rs.Fields(0) ' prints as expected
QueryDB2 = rs.Fields(0)
' close connections
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Function
If testQuery is a simple query (e.g., does not use UNION), then data is returned as expected. However, if the testQuery contains a UNION, then the Excel VBA code fails (and no particular error is returned). How can I work-around this issue? I'd like to avoid writing the SQL statement in VBA.
Consider using ADO's Open Recordset method. Usually, Execute are for action commands (append/update/delete, stored procedures, etc.). Additionally, if Execute returns a recordset it is only a forward-only (i.e, snapshot with no cursor), read-only recordset without the facilities of MoveNext, RecordCount, Update.
Dim cn As Object
Dim rst As Object
Dim strConnection As String
Set cn = CreateObject("ADODB.Connection")
Set rst = CreateObject("ADODB.Recordset")
' Hard code database location and name
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\server1\myDatabase.mdb"
' Open the db connection
cn.Open strConnection
' Open the recordset
rst.Open "testQuery", cn
Sheets(1).Range("A2").CopyFromRecordset rst
' Close recordset and db connection
rst.Close
cn.Close
Are you still struggling with this? Try using an ODBC Query. Follow the steps listed here.
http://translate.google.pl/translate?js=n&prev=_t&hl=pl&ie=UTF-8&layout=2&eotf=1&sl=pl&tl=en&u=http%3A%2F%2Fafin.net%2FKsiazkaSQLwExcelu%2FGraficznyEdytorZapytanSqlNaPrzykladzieMsQuery.htm
Make sure you have no nulls in your Union and if you do, you must use the NZ Function to convert nulls into zeros.

VBA Connection from Excel 2010 to SQL Server 2008

i'm pretty new to SQL and VBA, so please forgive any audacity the code below may contain. I am working with code written in Excel's VBA. Eventually, the data from the user form in excel will be entered into a SQL database I have created using SQL Server 2008. Right now, I am just trying to open the connection to the SQL database and enter hard coded values into the db. Unfortunately, this has been much more of a challenge than I expected. I have tried playing around with the connection string a few different ways but have had no luck. When the form runs, I get no errors and I can see the data was added into the appropriate excel worksheet (but no changes in the SQL DB). I can see the db on SQL Server Management Studio and add rows from there, but I am unable to add a row to the db via this code. The db is protected solely by windows authentication. Any help would be greatly appreciated.
Sub ConnectSqlServer()
'********SPC DATABASE CONNECTION**********************
'write slurry information to database
'spc_date, mix_type, slurry_lot_num, mixer_num, shift, oper
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
'Create connection string
sConnString = "Provider=sqloledb; Server=SERV; Database=db; Trusted_Connection=True;"
'Create the Connection and Recordset objects
Set oConn = New ADODB.Connection
Set rs = New ADODB.Recordset
'Open connection and execute
conn.Open sConnString
Set rs = conn.Execute("INSERT INTO TBL (col1, col2) VALUES ('val', 'val');")
'Clean up
If CBool(conn.State And adStateOpen) Then conn.Close
Set conn = Nothing
Set rs = Nothing
End Sub
When inserting data, you don't need a recordset object, since an INSERT statement doesn't return a recordset. Instead, try using a command object instead. The command object gives you more control over how your SQL statement is passed to the server, and it also gives you a way to test whether any records were inserted.
I'd also recommend setting Option Explicit at the top of each module, since it will stop you from making mistakes with variables (for instance, you have both conn and oConn in your code, which I don't think you intended.
Here are my edits to your code. It's untested, but I think I've got it right. If it runs without any errors, and recordsAffected returns 1, but there's still nothing on the server, then we'll have to do some more digging.
Sub ConnectSqlServer()
'********SPC DATABASE CONNECTION**********************
'write slurry information to database
'spc_date, mix_type, slurry_lot_num, mixer_num, shift, oper
Dim conn As New ADODB.Connection
Dim cmd As New ADODB.Command
Dim sConnString As String
Dim recordsAffected as Long
'Create connection string
sConnString = "Provider=sqloledb; Server=SERV; Database=db; Trusted_Connection=True;"
'Open connection and execute
conn.Open sConnString
With cmd
.ActiveConnection = conn
.CommandType = adCmdText
.CommandText = "INSERT INTO TBL (col1, col2) VALUES ('val', 'val');"
.Execute recordsAffected 'Includes a return parameter to capture the number of records affected
End With
Debug.Print recordsAffected 'Check whether any records were inserted
'Clean up
If CBool(conn.State And adStateOpen) Then conn.Close
Set cmd = Nothing
Set conn = Nothing
End Sub

Execute Query from Access via Excel Query in VBA

Access has saved a query that was designed with the query builder called 'myQuery'. The database is connected to the system via ODBC connection. Macros are all enabled.
Excel Has makes a ADODB connection to connect to the database via
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Set con = New ADODB.Connection
With con
.Provider = "Microsoft.ACE.OLEDB.12.0"
.Open "MyDatabase.accdb"
End With
Usually you would go ahead and just write your SQL, which is perfectly fine and then just do something like
Dim sqlQuery As String
sqlQuery = "SELECT * FROM myTable"
Set rs = New ADODB.Recordset
rs.Open sqlQuery, con, ...
But I want to access the query that I saved in the access database. So how do I call the saved query in the database that I just connected.
Tried already
con.Execute("EXEC myQuery") but that one told me it could not be find myQuery.
rs.Open "myQuery", con but that one is invalid and wants SELECT/etc statements from it
I think you can treat it like a stored procedure.
If we start right before Dim sqlQuery As String
Dim cmd as new ADODB.Command
cmd.CommandType = adCmdStoredProc
cmd.CommandText = "myQuery"
cmd.ActiveConnection = con
Set rs = cmd.Execute()
Then pickup your recordset work after this.
You were nearly there:
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Set con = New ADODB.Connection
With con
.Provider = "Microsoft.ACE.OLEDB.12.0"
.Open "z:\docs\MyDatabase.accdb"
End With
con.Execute "MyQuery"
Just leave out Exec.
You can add parameters, too, this is a little old, but should help: update 2 fields in Access database with Excel data and probably a Macro
I was able to run an update query that was already saved in Access using:
Connection.Execute "My_Update_Query_Already_Saved_In_Access", adExecuteNoRecords, adCmdStoredProc
This gave me errors until I replaced spaces in the query name with underscores in both the Access database and the execute statement.
This is sort of a hack job, but you can query a query. That is, replace your sql string with the following:
sqlQuery = "SELECT * FROM QueryName;"
Before running this, one must ensure that the Access Database has been saved ie. press Ctrl+S (it is not sufficient that the query was run in Access).
Long time since this thread was created. If I understand it correctly, I might have something useful to add. I've given a name to what the OP describes, that being the process of using SQL from a query saved in an ACCDB to run in VBA via DAO or ADOBD. The name I've given it is "Object Property Provider", even with the acronym OPP in my notes, and for the object name prefix/suffix.
The idea is an existing object in an ACCDB (usually a query) provides a property (usually SQL) that you need to use in VBA. I slapped together a function just to suck SQL out of queries for this; see below. Forewarning: sorry, but this is all in DAO, I don't have much use for ADODB. Hope you will still find the ideas useful.
I even went so far as to devise a method of using/inserting replaceable parameters in the SQL that comes from these OPP queries. Then I use VBA.Replace() to do the replacing before I use the SQL in VBA.
The DAO object path to the SQL of a query in an ACCDB is as follows:
mySqlStatement = Access.Application.CurrentDb.QueryDefs("myQueryName").SQL
The way I use replaceable parameters is by evaluating what needs to be replaced, and choosing an unusual name for the paramater that cannot possibly exist in the real database. For the most part, the only replacements I've made are field or table names, or the expressions of WHERE and HAVING clauses. So I name them things like "{ReplaceMe00000001}" and then use the Replace() function to do the work...
sqlText = VBA.Replace(sqlText, "{ReplaceMe00000001}", "SomeActualParameter")
...and then use the sqlText in VBA. Here's a working example:
Public Function MySqlThing()
Dim sqlText as String
Dim myParamater as String
Dim myExpression as String
'Set everything up.
sqlText = getSqlTextFromQuery("myQuery")
myParameter = "{ReplaceMe00000001}"
myExpression = "SomeDateOrSomething12/31/2017"
'Do the replacement.
sqlText = VBA.Replace(sqlText, myParameter, myExpression)
'Then use the SQL.
db.Execute sqlText, dbFailOnError
End Function
Function getSqlTextFromQuery(ByVal oppName As String) As String
Dim app As Access.Application
Dim db As DAO.Database
Dim qdefs As DAO.QueryDefs
Dim qdef As DAO.QueryDef
Dim sqlText As String
Set app = Access.Application
Set db = app.CurrentDb
Set qdefs = db.QueryDefs
Set qdef = qdefs(oppName)
oppGetSqlText = qdef.SQL
End Function