VBA to connect to SQL Server

VidyaKruthi

New Member
Joined
Feb 17, 2012
Messages
18
Hi All Good Evening,

Please help me out how to connect to SQL Server and get data using VBA.
 

Excel Facts

How to create a cell-sized chart?
Tiny charts, called Sparklines, were added to Excel 2010. Look for Sparklines on the Insert tab.
Tools -> References -> Microsoft ActiveX Data Objects 2.8 Library

Code:
Sub ConnectSqlServer()

    Dim conn As ADODB.Connection
    Dim rs As ADODB.Recordset
    Dim sConnString As String
 
    ' Create the connection string.
    sConnString = "Provider=SQLOLEDB;Data Source=INSTANCE\SQLEXPRESS;" & _
                  "Initial Catalog=MyDatabaseName;" & _
                  "Integrated Security=SSPI;"
    
    ' Create the Connection and Recordset objects.
    Set conn = New ADODB.Connection
    Set rs = New ADODB.Recordset
    
    ' Open the connection and execute.
    conn.Open sConnString
    Set rs = conn.Execute("SELECT * FROM Table1;")
    
    ' Check we have data.
    If Not rs.EOF Then
        ' Transfer result.
        Sheets(1).Range("A1").CopyFromRecordset rs
    ' Close the recordset
        rs.Close
    Else
        MsgBox "Error: No records returned.", vbCritical
    End If

    ' Clean up
    If CBool(conn.State And adStateOpen) Then conn.Close
    Set conn = Nothing
    Set rs = Nothing
    
End Sub

For more info about connection strings: http://www.connectionstrings.com
 
Last edited:
Upvote 0
Tools -> References -> Microsoft ActiveX Data Objects 2.8 Library

Code:
Sub ConnectSqlServer()

    Dim conn As ADODB.Connection
    Dim rs As ADODB.Recordset
    Dim sConnString As String
 
    ' Create the connection string.
    sConnString = "Provider=SQLOLEDB;Data Source=INSTANCE\SQLEXPRESS;" & _
                  "Initial Catalog=MyDatabaseName;" & _
                  "Integrated Security=SSPI;"
    
    ' Create the Connection and Recordset objects.
    Set conn = New ADODB.Connection
    Set rs = New ADODB.Recordset
    
    ' Open the connection and execute.
    conn.Open sConnString
    Set rs = conn.Execute("SELECT * FROM Table1;")
    
    ' Check we have data.
    If Not rs.EOF Then
        ' Transfer result.
        Sheets(1).Range("A1").CopyFromRecordset rs
    ' Close the recordset
        rs.Close
    Else
        MsgBox "Error: No records returned.", vbCritical
    End If

    ' Clean up
    If CBool(conn.State And adStateOpen) Then conn.Close
    Set conn = Nothing
    Set rs = Nothing
    
End Sub

For more info about connection strings: http://www.connectionstrings.com
It has taken me ages to find a straightforward example like this to work from.

Thanks very much for helping me clear this hurdle.
 
Upvote 0
Hello
This looks exactly like what I need.

I'm very new to all these database stuff and many things which are logical to you are difficult to understand for me.

But hopefully you can help me.

1.
Is the Provider allways the same?

2.
How can I find out my Data Source?

3.
How can I find out my Initial Catalog?

4.
Is there no User Name and Password necessary?


Thanks for your help!!!
 
Upvote 0
I feel a quick Acknowledgement and thanks is in order

This thread helped me a lot, thank you for that Sektor

For those slightly baffled at first like I was, here is how it's broken down:

Remember to go Tools > References and tick
Microsoft ActiveX Data Objects 2.8 Library (or higher)

In the part that says


Code:
sConnString = "Provider=SQLOLEDB;Data Source=INSTANCE\SQLEXPRESS;" & _
"Initial Catalog=MyDatabaseName;" & _
"Integrated Security=SSPI;"


Data Source is where your stuff is on whatever Server you're using. Ie,
Data Source=SERVER1\FOLDER (Don't go rooting around in Program Files for the .exe file for SQL Server 2008 like I did *facepalm*)

Initial Catalogue is whatever your database is called. Just change "
MyDatabaseName" to your own.

Sounds obvious I know but I'm totally new to this, as are many who view it!

Cheers!



 
Upvote 0
Sektor is my new hero! I have found numerous, convoluted methods to accomplish this task, but this one is simple and it WORKS!
 
Upvote 0
I feel a quick Acknowledgement and thanks is in order

This thread helped me a lot, thank you for that Sektor

For those slightly baffled at first like I was, here is how it's broken down:

Remember to go Tools > References and tick
Microsoft ActiveX Data Objects 2.8 Library (or higher)

In the part that says


Code:
sConnString = "Provider=SQLOLEDB;Data Source=INSTANCE\SQLEXPRESS;" & _
"Initial Catalog=MyDatabaseName;" & _
"Integrated Security=SSPI;"


Data Source is where your stuff is on whatever Server you're using. Ie,
Data Source=SERVER1\FOLDER (Don't go rooting around in Program Files for the .exe file for SQL Server 2008 like I did *facepalm*)

Initial Catalogue is whatever your database is called. Just change "
MyDatabaseName" to your own.

Sounds obvious I know but I'm totally new to this, as are many who view it!

Cheers!




Can anybody tell me how exactly you determine the replacement for SERVER1\FOLDER ? I mean SERVER1 is obviously the server name BUT what is FOLDER ? My db location is this: \Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA. What should I use instead of FOLDER ??? It seems this one is not that obvious...
 
Upvote 0
Can anybody tell me how exactly you determine the replacement for SERVER1\FOLDER ? I mean SERVER1 is obviously the server name BUT what is FOLDER ? My db location is this: \Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA. What should I use instead of FOLDER ??? It seems this one is not that obvious...

FOLDER is only important if you have a named instance of SQL Server other than the default on your server. For example, if your local computer name is COMP1, the default instance of SQL Server that installs would be COMP1, and you would not use anything else.
For your setup, it sounds like all you need to use is the server name.

On the other hand, if you have a named instance (for example, multiple instances of SQL Server on one PC), the FOLDER might be an instance name such as COMP1\SERVER2.
 
Upvote 0

Forum statistics

Threads
1,215,619
Messages
6,125,871
Members
449,267
Latest member
ajaykosuri

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