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

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

Related

How to solve this error SQL Server Network Interfaces: Connection string is not valid [87]

I am trying to connect sql server with vba using the code from a youtube tutorial video (https://www.youtube.com/watch?v=OWKae1pTTnE), but when i run the code to check if it works, I had an error openning the connections, Can you help me please? I have already install sql server 2019 and I have SQL Server Management Studio 18.
error: SQL Server Network Interfaces: Connection string is not valid [87]
Here is the code:
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Set cn = New ADODB.Connection
cn.ConnectionString = "Provider=MSOLEDBSQL;" & _
"Server=MyServer\MSSQLSERVER;" & _
"Database=master;" & _
"Trusted_Connection=yes;"
cn.Open 'The error occurs here
cn.Close
The solution that help wiht the issue above was provided by #Nick.McDermaid:
My error was in the Connection string, visiting the link:[1]: https://social.technet.microsoft.com/wiki/contents/articles/1409.how-to-create-a-sql-connection-string-for-an-application-udl-file.aspx?Redirected=true
It shows a simple steps to do the string conection based on the conditions that are needed. Once you follow the steps that and use it, works fine! In my case the solution looks like this:
Dim rs As ADODB.Recordset
Set cn = New ADODB.Connection
cn.ConnectionString = "Provider=SQLOLEDB.1;
Integrated Security=SSPI;
Persist Security Info=False;
Initial Catalog=MyDataBaseName;
Data Source=MyServer"
cn.Open 'The error that was here disappiers and runs fine'
cn.Close

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

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

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 :)!

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"

Connect to a linked table

Connect to a linked table with code.
I have some linked tables from a SQL-server; they are linked with an ODBC connection. The password is not saved with the connection. When I am double clicking on the table in Access table-view I get a prompt for username and password. After entering the password I can view the data in the table.
My problem is when I try to access the table with code before having opened it in this way. What I try to do is to use ADODB to open a recordset with data from the linked table, like:
Dim rst as new ADODB.Recordset
Dim sql as string
Sql = “SELECT * FROM LinkedTable”
rst.Open sql, CurrentProject.Connection, adOpenForwardOnly, adLockReadOnly
Running this code without having access the table before will generate this error: Error# -2147467259, ODBC: connection to dns-name failed.
So, my question is, are there any way to connect to the database with code that can be run when the database is opened? This would also help the users as they would not have to remember a password to the SQL-server.
It seems that you are mixing 2 technologies that might not work together, ie linked tables through ODBC and ADODB recordsets. Have you tried to open DAO recordsets on your linked tables?
Dim rst as DAO.Recordset
Dim sql as string
Sql = “SELECT * FROM LinkedTable”
set rst = currentDb.openRecordset(sql,<your parameters>)
You could of course use ADODB recordsets through 2 ADODB connections, one to your access file, the other one to your SQL server:
Dim rsSQL as ADODB.recordset, _
rsACCESS as ADODB.recordset, _
connectionSQL as ADODB.connection, _
connectionACCESS as ADODB.connection
set connectionSQL = New ADODB.connection
set connectionACCESS = New ADODB.connection
connectionSQL.properties(...) = enumerate your SQL parameters
connectionACCESS.properties(...) = enumerate your ACCESS parameters (use currentproject.accessConnection if your access tables are local tables only)
set rsSQl = New ADODB.recordset
set rsACCESS = New ADODB.recordset
rsSQL.open "SELECT * FROM ...", connectionSQL, <other parameters>
rsACCESS.open "SELECT * FROM ...", connectionACCESS, <other parameters>
Linking ADO recordsets to forms and comboboxes in Access is possible. But, when creating forms, this technology has to be mainly managed through VBA code (you will have to write 'on open' events such as set me.recorset = ...), while the standard "linked tables" technology can be easily used through the user-friendly 'form-design' interface.
You can use a connection string in your code, it is easy enough, seeing you are already using ADO: http://www.connectionstrings.com/
You will need to find out which version of SQL Server you are linking to.