Connect to SQL Server using DAO & VBA

gduron

Board Regular
Joined
Mar 27, 2006
Messages
94
I have a SQL Server that I would like to query for Excel to obtain certain records from. I have access to the Server and I will be running the VBA code locally on that machine at least for now. Can somebody please point me in the right direction as to how I can actually establish a connection with the SQL Server? I have added the reference library "Microsoft DAO 3.6 Object Library". I don't know anything about the variables I need to create or the methodology behind actually connecting to the SQL Server. I'm going to continue researching, but if somebody has a good tutorial on this or can give me some pointers I would greatly appreciate it.

Thanks in advance.
 

Excel Facts

Which lookup functions find a value equal or greater than the lookup value?
MATCH uses -1 to find larger value (lookup table must be sorted ZA). XLOOKUP uses 1 to find values greater and does not need to be sorted.
To the best of my knowledge DAO is better suited for Access databases . I'd use ADO as the better library for SQL Server connections these days.

You have more than one option.

1)
You can use Data | New Database Query... as a tool right in Excel. This will use a Data Source Name that you can save and re-use. See Zapawa's book Excel Advanced Report Development for the excellent resources on this, or keep posting your questions here.

2)
For ADO, there's a lot to learn at first although the basics are extremely simple. The first thing you'll need is a connection string and the proper authentications. Try this connection string trick and see if it works for you (otherwise, you can google connection strings and you'll find more info):

There's a lot of good info on ADO at W3 Schools. ADO has some three main objects (the Recordset object, the Connection object, and the Command object) and they can all be used to accomplish your task. The simplest is to use the Recordset object, but the Command object is capable of updates, deletes, and so on.

I also found Kimmel et al. Excel 2003 VBA to be very helpful with their chapter on ADO (specifically deals with SQL server as well - also where I found the trick posted in the link above).

Here's an example of an ADO routine. The only difference for you would be the connection string and the the SQL statement:
Code:
Sub GetDataFromAccessMDB()
'---------------------------------
'USER: Please make sure you set references to the ADO object Library
'     1. In the Visual Basic window select Tools on the main menu
'     2.  Then from the Tools menu select References...
'     3.  Then click the box for Microsoft ActiveX Data Objects
'     4.  If there is more than one choice, choose the highest version
'---------------------------------
    
    Const MY_DATABASE_PATH As String = _
        "\\Emc_nas\Users\David.Pecot\Ultra_Inventory 2007.mdb"

    Const strSQL = _
        "Select Top 5 Inventory.Year from Inventory;"

'Variables
Dim myRecordset As ADODB.Recordset
Dim strConnection_String As String

'Connection String
strConnection_String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
    "Data Source=" & MY_DATABASE_PATH & ";" & _
    "Persist Security Info=False"

'Object References
Dim ws As Worksheet
Set ws = Workbooks.Add.Sheets(1)
Set myRecordset = New ADODB.Recordset

'Initialize recordset and run the query
Call myRecordset.Open(strSQL, strConnection_String, CursorTypeEnum.adOpenForwardOnly, _
    LockTypeEnum.adLockReadOnly, CommandTypeEnum.adCmdText)

'Copy to worksheet
If Not myRecordset.EOF Then
    Call ws.Cells(1, 1).CopyFromRecordset(myRecordset)
End If

'Close recordset object and release memory
If (myRecordset.State And ObjectStateEnum.adStateOpen) Then myRecordset.Close
Set myRecordset = Nothing

End Sub

HTH
 
Upvote 0
Hi,

Thanks for your reply. i'm going to check out W3 Schools and keep checking things out on the web. In the meantime, I have found a lot of things on the web that show me how to connect to an Access File (Database) but I have yet to find a string that would enable me to connect to a SQL Server database.


Do you know how to modify this string to connect to a SQL Server database?

Const MY_DATABASE_PATH As String = _
"\\Emc_nas\Users\David.Pecot\Ultra_Inventory 2007.mdb"


If I discover the answer, I'll post it here.

Thanks
 
Upvote 0
These are from the site below and match other information on connection strings I’ve seen--there’s various options but what I have here is fairly standard I believe. Trusted connection would be if your windows ID authenticates you, rather than entering a password/ID to logon:
http://www.sqlstrings.com/SQL-Server-connection-strings.htm

Did you try my UDL connection string trick from my earlier post?

Standard Security:
"Provider=SQLOLEDB;Data Source=Your_Server_Name;Initial Catalog= Your_Database_Name;UserId=Your_Username;Password=Your_Password;"

Trusted connection:
"Provider=SQLOLEDB;Data Source=Your_Server_Name;Initial Catalog=Your_Database_Name;Integrated Security=SSPI;"
I would add (habit I guess):
"Persist Security Info=False;”
 
Upvote 0
As promised I found a way to do what I wanted and so I'm posting my response. I can't take credit for the response, as it was a professor who sent it to me from a school I attended. The response that he provided me. This is a working solution but you need to put in the username and password of the MS SQL Server you are trying to access and the code should be run locally on the machine/server where the database is stored. If you are trying to use access a machine on a remote server, I have included instructions in the comments on how to do so. This code will connect to the database Northwind but can be modified to connect to any database fairly easily by simply changing the name of the database and updating the sql statement.

Code:
Sub getData()
     Dim conn As Variant
     Dim rs As Variant
     Dim cs As String
     Dim query As String
     Dim row As Integer
 
     Set conn = CreateObject("adodb.connection")
     Set rs = CreateObject("adodb.recordset")
 
    'The database in this instance has been set as Northwind.
    'you will need to update the database for what yours is called.
    'The IP Address '127.0.0.1' represents localhost.  If you
    'are trying to connect to a remote sql server then you will
    'either need to enter the ip address or URL of that server.
    'In the connection string below, 1433 is the port number
    'the SQL server is listening on.  If your sql server is
    'listening on a different port you'll have to change it.
    '1433 is the default port for SQL Server.
    
 
          cs = "DRIVER=SQL Server;"
     cs = cs & "DATABASE=Northwind;"
     cs = cs & "SERVER=127.0.0.1,1433"
 
     'parameters here are connectionSring, username, password
     'you will need to put the actual username and password in
     'quotes here for this code to work.
     conn.Open cs, "<PUT_USER_NAME_HERE>", "<PUT_PASSWORD_HERE>"
 
     query = "select * from Customers"
     rs.Open query, conn
 
     row = 0
     Do Until rs.EOF
       row = row + 1
       Cells(row, 1).Value = rs.fields("ContactName").Value
       rs.movenext
     Loop
 
     rs.Close
     Set rs = Nothing
 
     conn.Close
     Set conn = Nothing
 
End Sub

Thanks for your help Alex. I did try the shortcut method but wasn't able to get it to work right. I might continue to play around with it in my spare time because it seems like a neat trick to know all the same.
 
Upvote 0
Thanks for posting back. It's good material to add to the board for future reference. --AB
 
Upvote 0
As promised I found a way to do what I wanted and so I'm posting my response. I can't take credit for the response, as it was a professor who sent it to me from a school I attended. The response that he provided me. This is a working solution but you need to put in the username and password of the MS SQL Server you are trying to access and the code should be run locally on the machine/server where the database is stored. If you are trying to use access a machine on a remote server, I have included instructions in the comments on how to do so. This code will connect to the database Northwind but can be modified to connect to any database fairly easily by simply changing the name of the database and updating the sql statement.

Code:
Sub getData()
     Dim conn As Variant
     Dim rs As Variant
     Dim cs As String
     Dim query As String
     Dim row As Integer
 
     Set conn = CreateObject("adodb.connection")
     Set rs = CreateObject("adodb.recordset")
 
    'The database in this instance has been set as Northwind.
    'you will need to update the database for what yours is called.
    'The IP Address '127.0.0.1' represents localhost.  If you
    'are trying to connect to a remote sql server then you will
    'either need to enter the ip address or URL of that server.
    'In the connection string below, 1433 is the port number
    'the SQL server is listening on.  If your sql server is
    'listening on a different port you'll have to change it.
    '1433 is the default port for SQL Server.
    
 
          cs = "DRIVER=SQL Server;"
     cs = cs & "DATABASE=Northwind;"
     cs = cs & "SERVER=127.0.0.1,1433"
 
     'parameters here are connectionSring, username, password
     'you will need to put the actual username and password in
     'quotes here for this code to work.
     conn.Open cs, "<PUT_USER_NAME_HERE>", "<PUT_PASSWORD_HERE>"
 
     query = "select * from Customers"
     rs.Open query, conn
 
     row = 0
     Do Until rs.EOF
       row = row + 1
       Cells(row, 1).Value = rs.fields("ContactName").Value
       rs.movenext
     Loop
 
     rs.Close
     Set rs = Nothing
 
     conn.Close
     Set conn = Nothing
 
End Sub

Thanks for your help Alex. I did try the shortcut method but wasn't able to get it to work right. I might continue to play around with it in my spare time because it seems like a neat trick to know all the same.
Over 5 years are you posted this, but was great for me!

thanks a lot
 
Upvote 0

Forum statistics

Threads
1,214,926
Messages
6,122,306
Members
449,079
Latest member
juggernaut24

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top