How do I connect to SQL Server using VBA? - sql-server

I want to automate some Mail Merge functionality using data drawn from a SQL Server Database. Here’s the code I’m using:
Sub open_DSN()
Dim strConnection As String
ActiveDocument.MailMerge.CreateDataSource Name:="DB-NAME", _
Connection:="Provider=SQLOLEDB.1;Persist Security Info=False;Initial Catalog=DB-NAME;Data Source=DATA-SOURCE", _
SQLStatement:="select * from DataTable"
ActiveDocument.MailMerge.OpenDataSource Name:="DB-NAME"
If ActiveDocument.MailMerge.DataSource.Name <> "" Then _
MsgBox ActiveDocument.MailMerge.DataSource.Name
' – code lifted from MS Help within Word that seems the nearest to what I require
'With ActiveDocument.MailMerge
' .MainDocumentType = wdFormLetters
' strConnection = "DSN=MS Access Databases;" _
' & "DBQ=C:\Northwind.mdb;" _
' & "FIL=RedISAM;"
' .OpenDataSource Name:="C:\NorthWind.mdb", _
' Connection:=strConnection, _
' SQLStatement:="SELECT * FROM Customers"
'End With
With ActiveDocument.MailMerge
.MainDocumentType = wdFormLetters
strConnection = "Provider=SQLOLEDB.1;Persist Security Info=False;Initial Catalog=DB-NAME;Data Source=DATA-SOURCE"
.OpenDataSource Name:="DB-NAME", _
Connection:=strConnection, _
SQLStatement:="SELECT * FROM DataTable"
End With
End Sub
Unfortunately I can’t get this code to display the data. What am I doing wrong?

Did you replace "DB-NAME" and "DATA-SOURCE" with the actual values in the connection string?

So do you have a sql server instance called DATA-Source with a Database called DB-Name?
Probably not?
More Like MyServer\MyInstance and MyDatabase

I don't know MailMerge, so I can't comment on the code that you use to establish the connection.
But if you are sure that the code is okay, then it's probably the connection string.
There are lots of different possible connection strings to connect to SQL Server, so the right solution depends on your SQL Server version and setup (for example, Windows authentification or SQL Server authentification...).
This MSDN article which says that MailMerge supports OLE DB and ODBC, so you can use either of these.
If you tell us more about your SQL Server setup, we can help you find the correct connection string for your use case.

Related

how to connect VBScript (Excel) to SQL Server web database (via IP)

I'm at my job trying to do some unknow stuff for me, you see, we're trying to connect an excel document with a VBScript Macro to a databse stored in web server but for some reason doesn't recognizes the user and throws an error repeatedly, i discarded a connection issue since it returns an SQL error instead of something like a timeout or server doesn't exists or something like that, we're trying to connect to the server using the ip address, we also checked that the logging method is on mixed (win and sql) and remotes connections to the server are enabled as well, also if i use the credentials provided in the connection string (username and password) i can actually log in to SQL Server without any issue, we also tried a direct connection (external vpn) because we thought it could be our firewall, but got the same error anyway, so we have no clue what it could be and we're kinda running out of ideas on how to do this, i'll post down below the code i'm using to trying the connection (obviously test data but similar to reality)
picture of the error i'm getting (don't post the original since it's in spanish but is very similar to this):
code i'm currently trying:
Sub excel_sqlsrv()
Set rs = CreateObject("ADODB.Recordset")
Set conn = CreateObject("ADODB.Connection")
strConn = "Driver={ODBC Driver 17 for SQL Server};Server=10.20.30.5;Database=mydb;UID=sa;PWD=abcd12345;"
conn.Open strConn
strSqL = "SELECT * FROM USERS"
rs.Open strSqL
End Sub
Any advice, tip or trick could be of tremendous help for me, i'll be looking forward to any kind of comment, thanks in advance
Use the ODBC Data Source Administrator to create a connection named mydb and test it works. Then use
Sub excel_sqlsrv()
Const strConn = "mydb" ' ODBC source
Const strsql = "SELECT * FROM USERS"
Dim conn As Object, rs As Object
Set rs = CreateObject("ADODB.Recordset")
Set conn = CreateObject("ADODB.Connection")
On Error Resume Next
conn.Open strConn
If conn.Errors.Count > 0 Then
Dim i, s
For i = 0 To conn.Errors.Count - 1
s = s & conn.Errors(i) & vbLf
Next
MsgBox s
Else
On Error GoTo 0
Set rs = conn.Execute(strsql)
Sheet1.Range("A1").CopyFromRecordset rs
End If
End Sub
You can try using OLEDB provider instead of ADODB.

Run Stored Procedure in SQL database from Access VBA without windows authentication

I am trying to run a stored procedure (using Access VBA) in the SQL database. I can find a few examples of this on SO and on other sites but what I am unable to find is connection string where I can provide my login details as windows authentication won't work because I have to use a different user to connect to SQL database
Here is what I have tried so far (got this from one of the post in SO, unfortunately, I can't find the post anymore):
Sub RunSQLProc()
Dim cdb As DAO.Database, qdf As DAO.QueryDef
Set cdb = CurrentDb
Set qdf = cdb.CreateQueryDef("")
qdf.Connect = "ODBC;" & _
"Driver=SQL Server;" & _
"Server=myServer;" & _
"Database=myDatabase;" & _
"UID=myUsername;" & _
"PWD=myPassword;" & _
"Trusted_Connection=yes;"
' "Driver={SQL Server Native Client 11.0};" & _
' "MARS Connection=True;"
qdf.SQL = "SQLStroedProcedure;"
qdf.ReturnsRecords = False
qdf.Execute dbFailOnError '<-- this line throws the error
Set qdf = Nothing
Set cdb = Nothing
End Sub
On qdf.Execute dbFailOnError line, I get the following error:
Run-time error '3151':
ODBC--connection to 'SQL ServermyServer'failed.
I have managed to connect to the SQL database and run the stored procedure through SQL Server Management Studio. This tells me that the details in my connection string are correct (although I haven't provided the actual details here) but I suspect there is an issue with my connection string.
Happy to provide more details. Any help is much appreciated, thanks
P.S. Apologies for my lack of knowledge in Access. I just don't use it very often
to use SQL Server security remove Trusted_Connection=yes.
https://www.connectionstrings.com/microsoft-sql-server-odbc-driver/

Excel Visual Basic ADODB SQL connection string not working

I'm trying to connect to an SQL Server through Automatisation in VBA, so each time Excel starts, the SQL Statement updates the table in Excel.
Problem is, that my Connection string always throws an exception:
"Run-time error "-2147217843 (80040e4d)'; Automation error"
I have following data provided:
Servername, though it has a comma in it's Name
Database Name
I also have a Windows user (accountname & Password), that I run the Statements from, but I doubt, it is necessary to provide this information to the SQL Server.
the Connection string Looks as follows:
Public Sub OpenConnection2(pServer As String, pCatalog As String)
Dim mDataBase As New ADODB.Connection
Dim mRS As New ADODB.Recordset
Dim mCmd As New ADODB.Command
Call mDataBase.Open("Provider=SQLOLEDB;Initial Catalog=" & pCatalog & ";Data Source=" & pServer & ";")
mCmd.ActiveConnection = mDataBase
End Sub
As you, FunnyO, already stated, it is the connection string.
You probably do not have the correct driver definition.
Try something like that:
strCnn = "Provider=SQLNCLI11;Server=" & pServer & ";Database=" & pCatalog & ";Integrated Security=SSPI;"
Sure, a very simple connection string. But it should work out as it is a very common one...

Set commandtimeout for linked SQL Tables/Views in Access front end

We have moved some back-end data tables over from a network drive (mbd file) to being on an SQL Server database. Things mostly work great, but if staff are accessing things through a VPN (which slows things down a lot), then we get connection errors when we run reports that retrieve a lot of data. My guess is that I need to set a timeout to a larger value, and I did some research and it seems that I need to set the commandtimeout (or maybe query timeout?).
Below is the VBA code we use to connect the SQL Server tables/views to our Access front end from the SQL Server back end. Am I right that I likely need to specify a commandtimeout? Where in this would we add the commandtimeout (or other timeout) value?
Public Sub CreateSQLLinkedTable(strSourceTableName As String, strNewTableName As String)
'************************************************************************************
'* Create a linked table in the current database from a table in a different SQL Server file.
'* In: *
'* strNewTableName - name of linked table to create *
'* strSourceTableName - name of table in database *
'************************************************************************************
Setup:
Dim tdf As TableDef
Dim strConnect As String, strMsg As String
Dim myDB As Database
' set database vars
Set myDB = CurrentDb
Set tdf = myDB.CreateTableDef(strNewTableName)
MakeConnections:
On Error GoTo OnError
' turn system warnings off
DoCmd.SetWarnings False
' define connect string and source table
' We do not need to specify the username (Uid) and password (Pwd) in this connection
' string, because that information is already cached from the connection to the SQL
' Projects database that we created in CheckSQLConnection() that was run to check connection
' to the database. So here we can have a connection string without the Uid and Pwd.
With tdf
.Connect = "ODBC;Driver={SQL Server};" & _
"server=" & myServer & ";" & _
"database=" & mySQLDB & ";"
.SourceTableName = strSourceTableName
End With
' execute appending the table
myDB.TableDefs.Append tdf
' turn system warnings back on
DoCmd.SetWarnings True
ExitProgram:
' this block of code will run if there are no errors
Exit Sub
OnError:
' this block of code runs if there is an error, per On Error assignment above
' display error message with details
MsgBox "There was an error connecting to the SQL Server data source Projects. Error = " & err & ", Description: " & err.Description
'exit Projects
Call CloseFormsAndQuit
End Sub
There is an ODBC timeout property. Open the query in design view, and go to properties to see it. There is also an (ODBC) query timeout on the current database properties page. You can set it programmatically as well:
Dim objDB As DAO.Database
Set objDB = CurrentDb()
objDB.QueryTimeout = 120
http://www.geeksengine.com/article/how-to-change-timeout-value-for-access-sql.html
Also check the server configuration. There is a query timeout on server side.

Cannot use pass through queries in Excel

I've scoured multiple forums for days now and still stuck. Hoping somebody can shed some light here.
I am increasingly frustrated by SQL syntax differences between MS Office and native SQL, and I've been led to believe that using pass through queries will allow me to use native SQL. I've tried multiple suggestions from various forums to create a pass through query, but I am still faced with Office (syntax) errors in my queries.
Below is a simple example of my code, which Excel/VBA does not like, due to the ISNULL syntax. Please note, it isn't ISNULL itself that is the problem, I know how to work around that. This is just by way of example. The problem is that it should work in native SQL (and it does in SQL Server Management Studio).
For completeness, I am using:
SQL Server 2014
MS Excel 2013
Microsoft DAO 3.6 Object library
I suspect the connection string or the DAO object library may be the culprit, but I've tried multiple others with the same result.
The complete sample (failing on OpenRecordSet) code follows. I would be eternally grateful for any help that can be offered.
Thanks,
Ryan
Option Explicit
Sub TestQuerySQL()
Dim sqlConnect As String, dsnName As String, dbName As String, sqlString As String, db As Database, qd As QueryDef, rs As Recordset
dsnName = "MyDSN"
dbName = "MyDatabaseName"
sqlConnect = "ODBC;DSN=" & dsnName & ";Trusted_Connection=yes;"
sqlString = "Select isnull(d.Name, '???') as DealerName from Dealer d"
Set db = OpenDatabase(dbName, dbDriverNoPrompt, True, sqlConnect)
On Error Resume Next
Set qd = db.CreateQueryDef("", sqlString)
If Err.Number <> 0 Then
MsgBox "CreateQueryDef failed. SQL=>" & sqlString & "< " & Err.Number & " Err=>" & Err.Description & "<", vbCritical
Else
qd.ReturnsRecords = True
Set rs = qd.OpenRecordset(dbOpenSnapshot, dbReadOnly)
If Err.Number <> 0 Then
MsgBox "OpenRecordset Failed. SQL=>" & sqlString & "< Err=>" & Err.Description & "<", vbCritical
Else
MsgBox "Success"
'do someting with the results
End If
End If
End Sub
Specify the dbSQLPassthrough option in the recordset line. Without this designation, the JET/ACE DAO Engine uses its own SQL dialect and hence interprets ISNULL() as the logical function and not SQL Server's ISNULL() as the value function. Below directly opens the recordset without using querydef:
DAO Connection
Set db = OpenDatabase(dbName, dbDriverNoPrompt, True, sqlConnect)
Set rs = db.OpenRecordset(sqlString, dbOpenDynaset, dbSQLPassThrough)
ADO Connection
Alternatively, use an ADO connection where any external SQL engine's dialect can be read:
Dim conn As New ADODB.Connection, rst As New ADODB.Recordset
Dim sqlConnect As String, sqlString As String
' REFERENCE THE MICROSOFT ACTIVEX DATA OBJECTS XX.X LIBRARAY '
sqlConnect = "ODBC;DSN=" & dsnName & ";Trusted_Connection=yes;"
sqlString = "Select isnull(d.Name, '???') as DealerName from Dealer d"
conn.Open sqlConnect
rst.Open sqlString, conn

Resources