简体   繁体   中英

How do I connect to SQL Server using VBA?

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?

您是否用连接字符串中的实际值替换了“ DB-NAME”和“ DATA-SOURCE”?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM