Access query called as stored procedure via ADO can't retrieve from linked tables - sql

I'm trying to use VBA from Excel 2007 to execute a query in an Access 2007 DB as a stored procedure. The query retrieves data from a few MS SQL tables linked via an ODBC DSN. The authentication for the external tables is done with Windows NT authentication with Trusted_Connection=Yes
I have tried connecting to the linked tables with both a User and System DSN - either way works fine when I run the query from Access 2007.
When I try using VBA in Excel the data that should be coming from the Windows authenticated tables isn't retrieved. I am able to retrieve data from a set of linked MS SQL tables that are using a stored UID.
Here is the connection string I'm using:
strDB = xlWb.Path & "\database\dbQueries.accdb"
conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & strDB & ";"
And here is the command that's only partially successful (with data from the UID authenticated tables):
With cmd2
.ActiveConnection = conn
.CommandText = "qryAppendtblOutput"
.CommandType = adCmdStoredProc
.Parameters.Append cmd2.CreateParameter("[Start Date]", adDBDate, adParamInput, , startDate)
End With
cmd2.Execute
Thanks very much in advance!

I have been able to resolve this issue by switching to the Access ODBC driver instead of the OLE DB provider. I changed my connection string to:
strDB = xlWb.Path & "\database\dbQueries.accdb"
conn.Open "Driver={Microsoft Access Driver (*.mdb, *.accdb)};" & _
"Dbq=" & strDB & ";" & _
"Trusted_Connection=Yes;"
Then, all I had to do was adjust the syntax of the underlying queries in Access to meet the requirements of this driver (I had to replace all double quotes with singles).
Thanks very much to all who reviewed my question :)!

Related

Excel VBA database access through ODBC not ADODB

I am working on an Excel file that connects to a SQL database to update parameters on a piece of production machinery based on an analysis of part quality data. The file has been working in production for some time but a recent hacking attack on my company has caused us to review the security of all of our systems.
The old file version used ADODB with a hard-coded user name a password with narrowly defined database permissions. This meant any quality or engineering employee could run the Excel utility without being explicitly given server/database access. With our new security review, I wanted to switch the file to use windows authentication but I ran into some issues. It seems that using windows authentication through ADODB requires not just a database user, the automation team has permissions to create, but also a server login mapped to the database user which only an IT admin can create. I also worry that adding a large number of server-level users is not a wonderful idea.
The actual piece of production equipment uses a system-level ODBC connection with window authentication. This connection works fine with a database user without a server login. Because ODBC doesn't seem to need a server login it would make the management of the Excel file users much simpler and would allow the team in charge of the equipment and its database to handle it without IT.
Unfortunately, I have been unable to figure out how to execute queries and get results in VBA with an ODBC connection. I have tried Workbook.Connections("ODBCName").CommandText with an ODBC connection stored in the workbook but I don't see a way to directly get the result. The only option I can see is to map the query to cells in a hidden table and read them in VBA but this seems hackish. Also, I'm not sure how this would work for the results of queries other than SELECT like INSERT or UPDATE.
Any help would be greatly appreciated. An example of my old code is here, there are more routines that make similar queries:
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open strCon
strSQL = "SELECT * FROM Table.dbo.PART_INSPECTION_LOG WHERE PART_NUM = 'PartNo' AND DATA_TIME = " & dataTime
rs.Open strSQL, cn
If (rs.BOF And rs.EOF) = True Then
linear_err = (Sheets("Adjustment").Range("E24").Value)
rotational_err = (Sheets("Adjustment").Range("N24").Value)
strSQL = "INSERT INTO Table.dbo.PART_INSPECTION_LOG (PART_NUM, TOOL_ID, USER_NAME, DATA_TIME, LINEAR_ERROR, ROTATIONAL_ERROR) VALUES ('PartNum', 'ToolNum', "
strSQL = strSQL & "'" & Application.UserName & "', "
strSQL = strSQL & dataTime & ", "
strSQL = strSQL & linear_err & ", "
strSQL = strSQL & rotational_err & ")"
cn.Execute strSQL
End If
cn.Close

Unable to connect to DB from VBA but able to connect from Access

I'm able to connect to a database using Access, but not from VBA. In Access, I use the server name, Windows NT Integrated Security,and the database name. In VBA, I've tried many variations of variable names and values in the connection string, and the db.Open command always fails. I generally get an error about not being able to find an installable ISAM, or Multiple-step OLE DB operation generated errors. Is there a way to determine what I can use as a connection string from the working Access connection? One example of code that fails with the latter error:
Dim db As Object
Dim adoRS As Object
Set db = CreateObject("ADODB.Connection")
Set adoRS = CreateObject("ADODB.recordset")
db.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Server=sql03;" & _
"Database=db1;" & _
"Integrated Security=SSPI;"
The provider you as using in the connection string is for MS Access.
If thats the correct database then do the following.
Add the refrence "Microsoft Office 14.0 Access Database Engine object library.
Dim cnString, query As String
Dim rs As New ADODB.Recordset
'If older version of MS access then try Provider=Microsoft.Jet.OLEDB.4.0;'
cnSTring= "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=<Path>;Jet OLEDB:Database Password=<Pass>;"
query = "SELECT * FROM TABLE"
rs.Open query, cnString, adOpenStatic, adLockOptimistic

submit data from excel userform to password protected access database

i am trying to submit userform data from excel (2013) to an access database.
without password, this code works fine.
Private Sub Addoer_Click()
Dim cnn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim dbPath
dbPath = Sheet16.Range("K18").Value
Set cnn = New ADODB.Connection
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data source=" & dbPath
Now i am trying to use same method to send data from excel to a password protected database (each user has different password). In the excel file, the user id is at Sheet16.Range("K17") and password is at Sheet16.Range("K19")
userid = Sheet16.Range("K17").Value
pw = Sheet16.Range("K19").Value
i changed the cnn.open line to following
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data source=" & dbPath, userid, pw, -1
and I am getting this error:
Error -2147217843 (Cannot start your application.The workgroup information file is missing or open exclusively by another User.)
i changed the cnn.open line to this
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data source=" & dbPath, """ & userid & """, """ & pw & """, -1
and I get this error
Error -2147217843 (Not a valid account name or password).
Is there anybody that can help to point where did I do wrong?
Your second attempt doesn't work, because you are passing in the username as "user" when the username is actually user.
Regarding your first attempt, I found this note at connectionstrings.com:
Note! Reports say that a database encrypted using Access 2010 - 2013 default encryption scheme does not work with this connection string. In Access; try options and choose 2007 encryption method instead. That should make it work.
Also, could it be that the database is opened exclusively by another connection / program? If you have the database open in Access and you can design tables / queries, IIRC that means you have exclusive access to the database, and no other connections can connect to it. Do you see an .laccdb (or .ldb) file in the same folder as the Access database?
References:
Microsoft OLE DB Proivder for Microsoft Jet
ConnectionString Property
Formatting Rules for Connection Strings at connectionstrings.com

Trying to connect to sql server 2012 from within Excel using ADODB connection

I have some code written in VBA. I need to query a table in a sql server 2012. I cannot get the connection to work. Below is what I have tried so far without any luck.
The error message I get is "Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done."
Dim cn As New ADODB.Connection
Dim cnString As String
cnString = "Provider=SQLOLEDB.1;" & _
"Server=MyServerName;" & _
"Initial Catalog=MyDatabaseName;" & _
"Integrated Security=False;"
cn.Open cnString, "myID", "myPassowrd"

VBScript to connect to SQL Server 2005 and update a table

I am new to VBScript. Can someone please help me to connect to SQL Server 2005 (OLEDB) using VBScript and update a table in the database.
My server: sql14\qw
My database: fret
User id: admin
Pasword: pass
Table name: lookup
Const DB_CONNECT_STRING = "Provider=SQLOLEDB.1;Data Source=sql14\qw;Initial Catalog=fret;user id ='admin';password='pass'"
Set myConn = CreateObject("ADODB.Connection")
Set myCommand = CreateObject("ADODB.Command" )
myConn.Open DB_CONNECT_STRING
Set myCommand.ActiveConnection = myConn
myCommand.CommandText = "UPDATE lookup SET Col1 = 'Hello'"
myCommand.Execute
myConn.Close
Tested using Integrated Windows Security, did not test with SQL Login.
Easy stuff, actually. First, you have to define the connection and recordset that you'll be using:
Set AdCn = CreateObject("ADODB.Connection")
Set AdRec = CreateObject("ADODB.Recordset")
After that, it's all about the connection string:
connstr="Provider=SQLOLEDB.1;Data Source=" & server & ";Initial Catalog=" & database & ";user id = '" & uid & "';password='" & pwd & "'"
The string consists of a few parts:
Provider: the type of connection you are establishing, in this case SQL Server.
Data Source: The server you are connecting to.
Initial Catalog: The name of the database.
user id: your username.
password: um, your password. ;)
Note that if you want to use your Windows login credentials and are running the script locally then you can substitute the following for the username and password fields:
Integrated Security=SSPI
Of course, this won't work if you're using your script on a website, so you'll have to explicitly use username and password. Then, making sure your connection is open, you just open the recordset, hand over the SQL query, and capture the returned data as an array.
SQL="Select ##version as name"
AdCn.Open connstr
AdRec.Open SQL, AdCn,1,1
queryReturn=Adrec("name")
Just remember that the data is being returned as an array (often two dimensional, where the results you want are actually in the second dimension of the array!) and that you may need to either Trim to kill blank spaces at the end of results or parse the results with string functions like Left. Personally, I always Trim() a result while assigning it to a variable as I've been bitten by hidden blanks more times than I can count.