简体   繁体   English

如何使用VBA连接到SQL Server?

[英]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. 我想使用从SQL Server数据库中提取的数据来自动化某些邮件合并功能。 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? 那么,您是否有一个名为DATA-Source的SQL Server实例以及一个名为DB-Name的数据库?

Probably not? 可能不是?

More Like MyServer\\MyInstance and MyDatabase 更像MyServer \\ MyInstance和MyDatabase

I don't know MailMerge, so I can't comment on the code that you use to establish the connection. 我不知道MailMerge,因此无法评论您用于建立连接的代码。
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...). 很多 不同的可能的 连接字符串可连接到SQL Server,因此正确的解决方案取决于您的SQL Server版本和设置(例如Windows身份验证或SQL Server身份验证...)。

This MSDN article which says that MailMerge supports OLE DB and ODBC, so you can use either of these. 这篇MSDN文章说MailMerge支持OLE DB和ODBC,因此您可以使用其中任何一种。
If you tell us more about your SQL Server setup, we can help you find the correct connection string for your use case. 如果您向我们介绍有关SQL Server设置的更多信息,我们可以帮助您找到适合您的用例的正确连接字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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