VBA in EXCEL - Connect to SQL Server

Embed Size (px)

Citation preview

  • 8/10/2019 VBA in EXCEL - Connect to SQL Server

    1/8

    28/05/13 VBA in EXCEL - Connect to SQL Server

    social.msdn.microsoft.com/Forums/en-US/isvvba/thread/f599f280-b786-43f4-9357-77f19a107c3f/ 1/8

    Microsoft Developer Network>Forums Home > Microsoft ISV Community Center Forums > Visual Basic for Applications (VBA) > VBA in EXCEL - Connect to SQL Server

    Search Visual Basic for Applications (V Ask a question

    0

    0

    VBA in EXCEL - Connect to SQL Server

    I am a new programmer try to write some VBA codes in excel to get data out from the Sql

    server database. When I try to compile the codes, it said "compile error: user defined typednot defined" for the following sentences

    Dim dbsCurrent As Database Dim qdfPassThrough As QueryDef Dim qdfLocal As QueryDef Dim rstTopFive As Recordset Dim strMessage As String

    What I need to define for Database,recordset or QueryDef? Please help!!!

    Reply Quote

    All Replies

    Ah.... I found an answer. I need to add the reference of DAO object library.

    But there is another problem.......

    sqlstring = "select * from customer"

    My Forum Links

    Sign In To Forums

    Forums Home

    Browse Forums Users

    Frequently asked questions - Forums helpRoda Chan 30 Points

    Thursday, April 13, 2006 1:52 AM

    Roda Chan 30 Points

    Thursday, April 13, 2006 4:42 AM

    Search MSDN with BingHome Library Learn Samples Downloads Support Community Forums

    United States (English) Sign in

    https://login.live.com/login.srf?wa=wsignin1.0&wtrealm=social.msdn.microsoft.com&wreply=https%3a%2f%2fwww.google.co.id%2f%3fprof%3drequired%26stoAI%3d10&wp=MBI_FED_SSL&wlcxt=microsoft%24microsoft%24microsofthttps://login.live.com/login.srf?wa=wsignin1.0&wtrealm=social.msdn.microsoft.com&wreply=https%3a%2f%2fwww.google.co.id%2f%3fprof%3drequired%26stoAI%3d10&wp=MBI_FED_SSL&wlcxt=microsoft%24microsoft%24microsofthttp://social.msdn.microsoft.com/profile/roda%20chan/?ws=usercard-minihttp://msdn.microsoft.com/http://msdn.microsoft.com/library/default.aspxhttp://msdn.microsoft.com/bb188199https://login.live.com/login.srf?wa=wsignin1.0&wtrealm=social.msdn.microsoft.com&wreply=https%3a%2f%2fwww.google.co.id%2f%3fprof%3drequired%26stoAI%3d10&wp=MBI_FED_SSL&wlcxt=microsoft%24microsoft%24microsofthttps://login.live.com/login.srf?wa=wsignin1.0&wtrealm=social.msdn.microsoft.com&wreply=https%3a%2f%2fsocial.msdn.microsoft.com%2fForums%2fen-US%2fisvvba%2fthread%2ff599f280-b786-43f4-9357-77f19a107c3f%2f%3fstoAI%3d10&wp=MBI_FED_SSL&wlcxt=microsoft%24microsoft%24microsofthttp://msdn.microsoft.com/en-US/SelectLocale?fromPage=http%3a%2f%2fsocial.msdn.microsoft.com%2fForums%2fen-US%2fisvvba%2fthread%2ff599f280-b786-43f4-9357-77f19a107c3f%2fhttp://social.msdn.microsoft.com/forums/en-us/categorieshttp://msdn.microsoft.com/aa497440http://msdn.microsoft.com/hh361695http://msdn.microsoft.com/aa570309http://code.msdn.microsoft.com/http://msdn.microsoft.com/bb188199http://msdn.microsoft.com/library/default.aspxhttp://msdn.microsoft.com/http://msdn.microsoft.com/en-UShttp://social.msdn.microsoft.com/profile/roda%20chan/?ws=usercard-minihttp://social.msdn.microsoft.com/profile/roda%20chan/?ws=usercard-minihttp://social.msdn.microsoft.com/Forums/en-US/helphttp://social.msdn.microsoft.com/Forums/en-US/browseusershttp://social.msdn.microsoft.com/Forums/en-US/categorieshttps://login.live.com/login.srf?wa=wsignin1.0&wtrealm=social.msdn.microsoft.com&wreply=https%3a%2f%2fsocial.msdn.microsoft.com%2fForums%2fen-US%2fisvvba%2fthread%2ff599f280-b786-43f4-9357-77f19a107c3f%2f%3fprof%3drequired%26stoAI%3d10&wp=MBI_FED_SSL&wlcxt=microsoft%24microsoft%24microsofthttp://social.msdn.microsoft.com/Forums/en-US/isvvba/thread/f599f280-b786-43f4-9357-77f19a107c3f?outputAs=rsshttps://login.live.com/login.srf?wa=wsignin1.0&wtrealm=social.msdn.microsoft.com&wreply=https%3a%2f%2fwww.google.co.id%2f%3fprof%3drequired%26stoAI%3d10&wp=MBI_FED_SSL&wlcxt=microsoft%24microsoft%24microsofthttps://login.live.com/login.srf?wa=wsignin1.0&wtrealm=social.msdn.microsoft.com&wreply=https%3a%2f%2fwww.google.co.id%2f%3fprof%3drequired%26stoAI%3d10&wp=MBI_FED_SSL&wlcxt=microsoft%24microsoft%24microsofthttp://social.msdn.microsoft.com/Forums/en-US/newthread?category=isvcommunitycenter&forum=isvvbahttp://social.msdn.microsoft.com/Forums/en-US/isvvba/threadshttp://social.msdn.microsoft.com/Forums/en-US/category/isvcommunitycenterhttp://social.msdn.microsoft.com/Forums/en-US/categorieshttp://msdn.microsoft.com/
  • 8/10/2019 VBA in EXCEL - Connect to SQL Server

    2/8

    28/05/13 VBA in EXCEL - Connect to SQL Server

    social.msdn.microsoft.com/Forums/en-US/isvvba/thread/f599f280-b786-43f4-9357-77f19a107c3f/ 2/8

    0

    connstring ="ODBC;UID=userid;PWD=password;DATABASE=db;DSN=datasource;dbDriverNoPrompt"With ActiveSheet.QueryTables.Add(Connection:=connstring, Destination:=Range("B1"),Sql:=sqlstring) .RefreshEnd With

    It always displays the ODBC Data Sourcesdialog box even though I have passed all theinformation in the connstring. Can anyone help please??

    Reply Quote

    Per our support engineer:

    We have Various ways to c onnect to a SQL server:

    - Using ADODB SQL ODBC provider with DSN

    - Using ADODB SQL ODBCprovider without DSN

    - ADO SQL OLEDB provider for authenticated connections

    In below code example, I've used the OLEDB provider for SQL using a trusted

    connection.

    ===

    Funct ion Get_BCM_Connection(Optional ByVal _

    ServerName As String = _

    "Percy\MicrosoftBCM") As ADODB.Connection

    'Returns an ADODB Connection object to Outlook 2003 Business Contact _

    'Manager installed locally

    '---------------------------------

    Dim cn As New ADODB.Connection

    MS ISV Buddy Team 4,945 Points

    Tuesday, April 25, 2006 3:13 PM

    http://social.msdn.microsoft.com/profile/ms%20isv%20buddy%20team/?ws=usercard-minihttps://login.live.com/login.srf?wa=wsignin1.0&wtrealm=social.msdn.microsoft.com&wreply=https%3a%2f%2fwww.google.co.id%2f%3fprof%3drequired%26stoAI%3d10&wp=MBI_FED_SSL&wlcxt=microsoft%24microsoft%24microsoft
  • 8/10/2019 VBA in EXCEL - Connect to SQL Server

    3/8

    28/05/13 VBA in EXCEL - Connect to SQL Server

    social.msdn.microsoft.com/Forums/en-US/isvvba/thread/f599f280-b786-43f4-9357-77f19a107c3f/ 3/8

    On Error GoTo ErrHand

    With cn

    .Connec tionString = "Provider=SQLOLEDB; " & _

    "Data Source=" & ServerName & "; " & _

    "Initial Catalog=MSBusinessContactManager;" & _

    "User ID=sa; Password=; Trusted_Connec tion=yes"

    .Open

    End With

    Set Get_BCM_Connect ion = cn

    ExitHere:

    On Error Resume Next

    cn.Close: Set cn = Nothing

    Err.Clear

    Exit Funct ion

    ErrHand:

    Set Get_BCM_Connect ion = Nothing

    MsgBox "Connect ion not propertly defined.", vbExclamation

    Resume ExitHere

    End Function

    ===

    And here is a KB :How To Import Data from Microsoft SQL Server intoMicrosoft Excel (http://support.microsoft.com/default.aspx?scid=kb;en-

    us;306125&sd=tech)

    I hope its helpful.

    -brenda (ISV Buddy Team)

    http://support.microsoft.com/default.aspx?scid=kb;en-us;306125&sd=tech
  • 8/10/2019 VBA in EXCEL - Connect to SQL Server

    4/8

    28/05/13 VBA in EXCEL - Connect to SQL Server

    social.msdn.microsoft.com/Forums/en-US/isvvba/thread/f599f280-b786-43f4-9357-77f19a107c3f/ 4/8

    0

    Reply Quote

    Due to an overlap in communication, I have more information on this topic that I might aswell post in case it helps someone.

    Using VBA to Get At SQL Server Data

    If you're after a less manual process, the last method is a bit more complex, but even more powerful.

    Microsoft Excel, like all newer versions of Microsoft Office products, has a com plete programming

    interface in the guise of Visual Basic for Applications (VBA). If you've got any programming experience

    at all, you can write code against a database.

    Again, all the previous warnings about locking apply. Additional warnings are warranted here, since

    with programming you can affect data in the database as well as reading from it.

    There are a few places you can use VBA in Excel, such as custom functions and macros, but we'll stick

    with macros for this example. The basic process is that you create a macro, edit it, and then run it.

    You edit the macro inside an editor, in which you type the code to connect, access, and close the

    connection to a database. Here's the process to create your own macro to connect to SQL Server

    programmatically:

    1. Open Excel.

    2. Click on Tools, then Macro, and then Macros...

    3. Name the Macro, and then click Create.

    4. In the editor window, type the following information, substituting the proper names for the

    server and the tables you want in between the "Sub xxxx" and "End Sub" tags:

    ' Declare the QueryTable objectDim qt As QueryTable' Set up the SQL Statementsqlstring = "select au_fname, au_lname from authors"' Set up the connection string, reference an ODBC connection' There are several ways to do this' Leave the name and password blank for NT authenticationconnstring = _

    MS ISV Buddy Team 4,945 Points

    Tuesday, May 09, 2006 3:42 PM

    http://social.msdn.microsoft.com/profile/ms%20isv%20buddy%20team/?ws=usercard-minihttps://login.live.com/login.srf?wa=wsignin1.0&wtrealm=social.msdn.microsoft.com&wreply=https%3a%2f%2fwww.google.co.id%2f%3fprof%3drequired%26stoAI%3d10&wp=MBI_FED_SSL&wlcxt=microsoft%24microsoft%24microsoft
  • 8/10/2019 VBA in EXCEL - Connect to SQL Server

    5/8

    28/05/13 VBA in EXCEL - Connect to SQL Server

    social.msdn.microsoft.com/Forums/en-US/isvvba/thread/f599f280-b786-43f4-9357-77f19a107c3f/ 5/8

    "ODBC;DSN=pubs;UID=;PWD=;Database=pubs"' Now implement the connection, run the query, and add' the results to the spreadsheet starting at row A1With ActiveSheet.QueryTables.Add(Connection:=connstring, Destination:=Range("A1"), Sql:=sqlstring).Refresh

    End With

    Save and close the macro, and run it from the same menu you accessed in step 2.

    NOTE

    There are probably at least ten programmatic ways to do this exact same thing and all of them are

    correct! If you're really interested in programming using VBA, you'll find several good books here at

    InformIT and also on Safari.

    Keeping The Database Connection Live

    We now move away from the "T ransfer In and Out" category to the "Linked Data" category of m ethods.

    I'll describe the two main methods to link data, both of which link Excel data into a SQL Server query.

    There are ways to use Excel to manage data directly in SQL Server, but they involve a bit more

    programming, and I've found them to be a bit clumsy especially for daily use. Excel simply doesn't

    handle locks and connectivity issues as well as you need for large-scale production solutions.

    You could also code a solution that accesses data stored in an Excel spreadsheet and update a SQL

    Server table as a result, but this is really event-driven and not a linked solution. (Again, there's a great

    deal of programming help in that vein here on InformIT.)

    So returning to the methods I've found easy to implement, there is a two-step process you can use to

    query data in an Excel spreadsheet.

    First, you'll need to c reate a linked server. Here's how to do that:

    1. Open Query Analyzer.

    2. Run the following code:

    -- Here we set up the linked server using the JET providerEXEC sp_addlinkedserver N'ExcelLink',@srvproduct = N'',

    @provider = N'Microsoft.Jet.OLEDB.4.0',@datasrc = N'C:\temp\test.xls',

  • 8/10/2019 VBA in EXCEL - Connect to SQL Server

    6/8

    28/05/13 VBA in EXCEL - Connect to SQL Server

    social.msdn.microsoft.com/Forums/en-US/isvvba/thread/f599f280-b786-43f4-9357-77f19a107c3f/ 6/8

    @provstr = N'Excel 8.0;'

    GO

    By doing so, you create a linked server, and give that connection a name. Notice also the name of the

    spreadsheet, which can also be a share location. You only have to do this once for each spreadsheet; if

    you're not going to access that spreadsheet again, it's a good idea to drop the linked server after you've

    used it.

    Now that we have a linked server, we can access the data. The process for this method is as follows:

    1. In a query tool such as Query Analyzer, type the following:

    -- Setup the user connection for the spreadsheetEXEC sp_addlinkedsrvlogin 'ExcelLink', 'false'GO-- Get the spreadsheet data - SCHOOLSP is the tab nameSELECT * FROM OPENQUERY(ExcelLink, 'select * from [SCHOOLSP$]')

    GO

    In this section, we've used the OPENQUERY function, which passes the query on to the provider. You'll

    find the query language is pretty limited at tim es, with Excel. If the queries aren't selective enough, set

    up another worksheet in the workbook with the data you want, and query that one.

    As you can see, you have several options open to integrate data between Microsoft Excel and SQL

    Server. Keep the limitations in mind, and get that data out there!

    Online Resources

    These links are from Microsoft. There are several others out there but these deal with some of the issues

    that I brought up in the article.

    Here's an article that details the data type woes with DTS and Excel imports.

    This article from Microsoft details the process of using DTS with Excel.

    Microsoft has a larger discussion of ODBC to Excel datatype issues here.

    This Microsoft articledetails programming w ith ADO against Excel files it shows you how to open one

    as a database.

    http://support.microsoft.com/default.aspx?scid=kb;EN-US;257819http://msdn.microsoft.com/library/default.asp?url=/library/en-us/odbc/htm/odbcjetsdk_43.asphttp://support.microsoft.com/default.aspx?scid=kb;en-us;Q319951http://support.microsoft.com/default.aspx?scid=kb;en-us;236605
  • 8/10/2019 VBA in EXCEL - Connect to SQL Server

    7/8

    28/05/13 VBA in EXCEL - Connect to SQL Server

    social.msdn.microsoft.com/Forums/en-US/isvvba/thread/f599f280-b786-43f4-9357-77f19a107c3f/ 7/8

    0

    0

    0

    -brenda (ISV Buddy Team)

    Reply Quote

    Thanks for posing this!

    You seemed to have stopped in mid stream.Can you provide the steps for the following?:

    ' Now implement the connection, run the query, and add

    ' the results to the spreadsheet starting at row A1

    ???

    Reply Quote

    Thanks for posing this!

    You seemed to have stopped in mid stream.Can you provide the steps for the following?:

    ' Now implement the connection, run the query, and add

    ' the results to the spreadsheet starting at row A1

    ???

    Reply Quote

    A little late to help this situation but for anyone else with a similar problem of having the ODBC

    Data Sources dialog box open every time they execute code to return query data. I've found

    this issue is due to the fact that the QueryTable "Save Password" has not been set to "True"

    mayberce 0 Points

    Friday, May 01, 2009 5:23 PM

    mayberce 0 Points

    Friday, May 01, 2009 5:24 PM

    Daniel_DeHavenTualatin Valley Fire And... 165 Points

    Tuesday, January 18, 2011 7:23 PM

    http://social.msdn.microsoft.com/profile/daniel_dehaven/?ws=usercard-minihttp://social.msdn.microsoft.com/profile/mayberce/?ws=usercard-minihttp://social.msdn.microsoft.com/profile/mayberce/?ws=usercard-minihttps://login.live.com/login.srf?wa=wsignin1.0&wtrealm=social.msdn.microsoft.com&wreply=https%3a%2f%2fwww.google.co.id%2f%3fprof%3drequired%26stoAI%3d10&wp=MBI_FED_SSL&wlcxt=microsoft%24microsoft%24microsofthttps://login.live.com/login.srf?wa=wsignin1.0&wtrealm=social.msdn.microsoft.com&wreply=https%3a%2f%2fwww.google.co.id%2f%3fprof%3drequired%26stoAI%3d10&wp=MBI_FED_SSL&wlcxt=microsoft%24microsoft%24microsofthttps://login.live.com/login.srf?wa=wsignin1.0&wtrealm=social.msdn.microsoft.com&wreply=https%3a%2f%2fwww.google.co.id%2f%3fprof%3drequired%26stoAI%3d10&wp=MBI_FED_SSL&wlcxt=microsoft%24microsoft%24microsoft
  • 8/10/2019 VBA in EXCEL - Connect to SQL Server

    8/8

    28/05/13 VBA in EXCEL - Connect to SQL Server

    social.msdn.microsoft.com/Forums/en-US/isvvba/thread/f599f280-b786-43f4-9357-77f19a107c3f/ 8/8

    via code, or manually you can set this in the Connection Properties dialog box.

    As long as you are supplying the password with code and have the "Save Password" property

    set to True (or checked in the dialog box) then the ODBC Data Sources dialog box should only

    appear the first time you execute the code, and sometimes it doesn't display even on the first

    time as long as you have the ODBC connection set-up on your machine.

    Dan

    Reply Quote

    TOOLS

    Visual Studio

    Expression

    ASP.NET

    Silverlight

    PLATFORMS

    Visual Studio

    Windows

    Windows Phone

    Windows Azure

    Office

    SERVERS

    Windows Server

    Exchange Server

    SQL Server

    Biz Talk Server

    Data

    DEVELOPER RESOURCES

    MSDN Subscriptions

    MSDN Magazine

    MSDN Flash Newsletter

    Code Samples

    MSDN Forums

    GET STARTED FOR FREE

    MSDN evaluation center

    BizSpark (for startups)

    DreamSpark (for students)

    School faculty

    2013 Microsoft. All rights reserved.Newsletter | Contact Us | Privacy Statement | Terms of Use | Trademarks | Site Feedback

    http://void%280%29/http://www.microsoft.com/About/Legal/EN/US/IntellectualProperty/Trademarks/EN-US.aspxhttp://msdn.microsoft.com/en-US/cc300389.aspxhttp://privacy.microsoft.com/en-us/default.mspxhttp://msdn.microsoft.com/en-us/subscriptions/aa948875.aspxhttp://msdn.microsoft.com/en-us/newsletter.aspxhttps://www.microsoft.com/facultyhttps://www.dreamspark.com/http://www.microsoft.com/bizspark/http://msdn.microsoft.com/evalcenter/default.aspxhttp://msdn.microsoft.com/evalcenter/default.aspxhttp://social.msdn.microsoft.com/forums/en-us/categorieshttp://code.msdn.microsoft.com/http://msdn.microsoft.com/aa570311http://msdn.microsoft.com/magazine/default.aspxhttp://msdn.microsoft.com/subscriptions/default.aspxhttp://msdn.microsoft.com/subscriptions/default.aspxhttp://msdn.microsoft.com/data/default.aspxhttp://msdn.microsoft.com/biztalk/default.aspxhttp://msdn.microsoft.com/sqlserver/default.aspxhttp://msdn.microsoft.com/exchange/default.aspxhttp://msdn.microsoft.com/windowsserver/default.aspxhttp://msdn.microsoft.com/windowsserver/default.aspxhttp://msdn.microsoft.com/office/default.aspxhttp://www.windowsazure.com/en-us/develop/overview/https://dev.windowsphone.com/http://msdn.microsoft.com/windows/apps/default.aspxhttp://msdn.microsoft.com/vstudio/default.aspxhttp://msdn.microsoft.com/vstudio/default.aspxhttp://msdn.microsoft.com/silverlight/http://www.asp.net/http://expression.microsoft.com/default.aspxhttp://msdn.microsoft.com/vstudio/default.aspxhttp://msdn.microsoft.com/vstudio/default.aspxhttp://stackoverflow.com/users/499733/daniel-dehaven