简体   繁体   English

使用 VBA 代码将 MS Word 邮件合并到 MS SQL 服务器的最简单方法是什么?

[英]What's the easiest way to MailMerge MS Word to MS SQL Server using VBA code?

Why doesn't MS Word just use a Connection String and SQL statement like every other platform on the planet?为什么 MS Word 不像地球上所有其他平台一样只使用连接字符串和 SQL 语句?

There are pretty standard connection strings to be used to connect to any database whether it's Access, MS Sql, MySql, etc. Whether you're coming from Ado in prehistoric VB, or ADO.net or EF, or Java, or Python, or PHP, etc. It's always the same. There are pretty standard connection strings to be used to connect to any database whether it's Access, MS Sql, MySql, etc. Whether you're coming from Ado in prehistoric VB, or ADO.net or EF, or Java, or Python, or PHP,等等。它总是一样的。 One simple Connection String, then the SQL to be executed.一个简单的连接字符串,然后执行 SQL。 Why is MS Word that much different?为什么 MS Word 如此不同?

I've had an Access front end to a SQL backend running for 20 years.我有一个访问前端到 SQL 后端运行了 20 年。 One of its functions sets up a Word Document with a MailMerge bound back to the Access front end.它的功能之一是设置一个 Word 文档,其中包含绑定回 Access 前端的 MailMerge。 The upgrade to Office 11 (or whatever the latest upgrade was) made that function start throwing an exception "Datasource placed in a state by admin".升级到 Office 11(或任何最新升级)使得 function 开始引发异常“管理员将数据源放置在 state 中”。 The only fix was to massage the ActiveDocument.MailMerge.OpenDataSource method so that it now uses DDE to connect to the access database.唯一的解决方法是修改ActiveDocument.MailMerge.OpenDataSource方法,以便它现在使用 DDE 连接到访问数据库。 The issue is that it freezes the computer for about 90 seconds.问题是它会冻结计算机大约 90 秒。

I'm thinking that it might just be simpler to point the MailMerge directly as the SQL backend.我认为将 MailMerge 直接指向 SQL 后端可能会更简单。 Any help would be appreciated.任何帮助,将不胜感激。

Difficult to know which is the "easiest way" for you, but here are the basics.很难知道哪种方法对您来说是“最简单的方法”,但这里有一些基础知识。 As you probably know, making database connections from Word can be very tricky - it's almost impossible to provide a completely reliable set of instructions that will definitely work.您可能知道,从 Word 建立数据库连接可能非常棘手 - 几乎不可能提供一套完全可靠且绝对有效的指令。 But Excel is generally much better at it so if you have problems it is worth seeing if your connection works on that.但是 Excel 通常在这方面要好得多,所以如果你有问题,值得看看你的连接是否有效。 (Although modern Excel makes it a lot harder to do that now, IMO). (尽管现代 Excel 使得现在这样做变得更加困难,IMO)。

To make an ODBC connection to a SQL Server data source from the current version of Windows desktop Word, you should be able to use one of the following.要从当前版本的 Windows 桌面 Word 与 SQL 服务器数据源建立 ODBC 连接,您应该能够使用以下方法之一。

Using a User DSN named SQLDSN that contains all the connection info (primarily driver name, instance\server name, DB name) for a database that is using Windows Authentication, and a table called MYTABLE, the starting point is straightforward:使用名为 SQLDSN 的用户 DSN,其中包含使用 Windows 身份验证的数据库的所有连接信息(主要是驱动程序名称、实例\服务器名称、数据库名称)和一个名为 MYTABLE 的表,起点很简单:

Sub c_odbc_user_dsn_1()
With ActiveDocument.MailMerge
  ' optionally disconnect any existing data source
  .MainDocumentType = wdNotAMergeDocument
  .OpenDataSource Name:="", _
    Connection:="DSN=SQLDSN;", _
    SQLStatement:="SELECT * FROM ""MYTABLE"""
End With
End Sub

Notes:笔记:

If the DSN is lacks some of the details or you are not using WIndows Authentication, you need to provide those details and username and password after SQLDSN;如果 DSN 缺少某些详细信息,或者您没有使用 WIndows 身份验证,则需要在SQLDSN; in the usual way, bearing in mind that you need to double up any double quote characters.以通常的方式,请记住您需要将任何双引号字符加倍。

I have only been able to make this work with a User DSN, not a System DSN.我只能使用用户 DSN 来完成这项工作,而不是系统 DSN。

You also need to use SQL Server's dialect of SQL, not Access Jet SQL.您还需要使用 SQL 服务器方言 SQL,而不是 Access Jet SQL。

You may also need to qualify the table name, eg using the full可能还需要限定表名,例如使用完整的

database_name.schema_name.table_name

syntax.句法。 If you have to do that, you may also encounter a problem where you have to quote each part of the name separately, eg something like如果您必须这样做,您可能还会遇到一个问题,即您必须分别引用名称的每个部分,例如

SQLStatement:="SELECT * FROM ""database_name"".""schema_name"".""table_name"""

You must specify a DSN.必须指定 DSN。 If you omit that but provide driver name, database name etc. only, it just doesn't work.如果您省略它但只提供驱动程序名称、数据库名称等,它就不起作用。 This is IMO the single most irritating aspect of Word ODBC connections.这是 IMO Word ODBC 连接中最令人讨厌的方面。

For some reason, Word does not retrieve any data from Unicode format columns (NTEXT, NCHAR, NVARCHAR) via ODBC.出于某种原因,Word 不会通过 ODBC 从 Unicode 格式列(NTEXT、NCHAR、NVARCHAR)中检索任何数据。 I have always believed it is a problem in Word.我一直认为这是Word中的问题。 Again, it is possible that there is some way to fix that using driver parameters but if so I do not know what that is.同样,可能有某种方法可以使用驱动程序参数来解决这个问题,但如果是这样,我不知道那是什么。 But if you don't have Unicode column types there should be no problem.但是如果你没有 Unicode 列类型应该没有问题。

At least one older version of Word would not let you specify "" as the file name in the OpenDataSOurce call.至少一个旧版本的 Word 不允许您在 OpenDataSOurce 调用中将“”指定为文件名。 Think it was fixed a while back though.认为它已经修复了一段时间。 Or it's possible that you had to provide an additional prameter to the call, like this:或者您可能必须为调用提供额外的参数,如下所示:

Sub c_odbc_user_dsn_2()
With ActiveDocument.MailMerge
  ' optionally disconnect any existing data source
  .MainDocumentType = wdNotAMergeDocument
  .OpenDataSource Name:="", _
    Connection:="DSN=SQLDSN;", _
    SQLStatement:="SELECT * FROM ""MYTABLE""", _
    SubType:=wdMergeSubTypeWord2000 ' i.e. :=8
End With
End Sub

If your SQLStatement exceeds around 255 characters, you have to split it in two and use this如果您的 SQLStatement 超过大约 255 个字符,则必须将其分成两部分并使用它

Sub c_odbc_user_dsn_3()
With ActiveDocument.MailMerge
  .MainDocumentType = wdNotAMergeDocument
  .OpenDataSource Name:="", _
    Connection:="DSN=SQLDSN;", _
    SQLStatement:="SELECT *", _
    SQLStatement2:=" FROM ""MYTABLE""", _
    SubType:=wdMergeSubTypeWord2000 ' i.e. :=8
End With
End Sub

IN fact, none of these parameters can exceed the 255 character limit so if you have a particularly long connection string you may need to cut some bits out of it.事实上,这些参数都不能超过 255 个字符的限制,因此如果您有一个特别长的连接字符串,您可能需要从中删除一些位。

If you have a File DSN, let's say at C:\my dsns\my sql server dsn.dsn then you should be able to start with this:如果你有一个文件 DSN,比如说C:\my dsns\my sql server dsn.dsn那么你应该可以从这个开始:

Sub c_odbc_file_dsn_1()
With ActiveDocument.MailMerge
  .MainDocumentType = wdNotAMergeDocument
  .OpenDataSource Name:="C:\my dsns\my sql server dsn.dsn", _
    Connection:="FILEDSN=C:\my dsns\my sql server dsn.dsn", _
    SQLStatement:="SELECT * FROM ""MYTABLE""", _
    SubType:=wdMergeSubTypeWord2000 ' i.e. :=8
End With
End Sub

In this case you definitely need the SubType parameter.在这种情况下,您肯定需要 SubType 参数。

Much the same issues as above, including the problem with Unicode columns.与上述问题大致相同,包括 Unicode 列的问题。

If you need Unicode columns, you have to use OLEDB.如果需要 Unicode 列,则必须使用 OLEDB。 There are a few ways to do it.有几种方法可以做到这一点。 Manually, make sure you have your connection info.手动,确保你有你的连接信息。 to hand, then in Word, use Mailings->Select Recipients->Use an Existing List , click the New Source... button near the bottom of the window, and you are then in the Data Connection Wizard.手,然后在 Word 中,使用Mailings->Select Recipients->Use an Existing List ,单击 window 底部附近的New Source...按钮,然后您将进入数据连接向导。 You may have several options.您可能有几个选择。

  • The "Microsoft SQL Server" option uses, I think, whatever provider Word assumes is the default.我认为, "Microsoft SQL Server"选项使用 Word 假定的任何提供程序都是默认设置。 Here, it is SQLOLEDB.1 .在这里,它是SQLOLEDB.1
  • The "ODBC DSN" option takes you to a second page that lets you choose an ODBC DSN. "ODBC DSN"选项将您带到第二页,让您选择 ODBC DSN。 This option uses the MSDASQL provider.此选项使用MSDASQL提供程序。 Interestingly, this route allows Word to see the Unicode column data that it can't see using ODBC alone.有趣的是,这条路线允许 Word 看到单独使用 ODBC 无法看到的 Unicode 列数据。 It also lets you use a System DSN.它还允许您使用系统 DSN。
  • The "Other/Advanced" option takes you to a list of OLE DB providers - you may have more than one for SQL Server. “其他/高级”选项将您带到 OLE DB 提供程序列表 - 您可能拥有多个用于 SQL 服务器的提供程序。

Once you have been through the dialogs, you are prompted to save your connection info in a.odc file.完成对话框后,系统会提示您将连接信息保存在 a.odc 文件中。 Word will let you finish making the connection, so in principle you might not need to use VBA. Word 会让你完成连接,所以原则上你可能不需要使用 VBA。 But if you do, all you actually need is something like this:但如果你这样做了,你真正需要的是这样的:

Sub c_oledb_1()
With ActiveDocument.MailMerge
  .MainDocumentType = wdNotAMergeDocument
  .OpenDataSource Name:="C:\my odcs\my sql server odc.odc", _
    SQLStatement:="SELECT * FROM ""MYTABLE"""
End With
End Sub

The.odc contains full connection info. .odc 包含完整的连接信息。 but some other items in it are a bit misleading.但其中的其他一些项目有点误导。 Also, Word uses the.odc once to make a connection.此外,Word 使用 .odc一次来建立连接。 If you save the Word Mail Merge Main document after that, and re-open it, Word re-opens the same connection, even if you changed the details in the.odc.如果您在此之后保存 Word Mail Merge Main 文档并重新打开它,Word 会重新打开相同的连接,即使您更改了 .odc 中的详细信息也是如此。 So if you need your document to reflect the changes, you have to disconnect/reconnect.因此,如果您需要文档来反映更改,则必须断开/重新连接。

If you have several OLE DB connections and you do not want to maintain/distribute several.odc files, you can use an empty.odc file (just a text file with no text and a.odc extension) and put the connection info in the Connection parameter.如果您有多个 OLE DB 连接并且您不想维护/分发多个.odc 文件,您可以使用一个空的.odc 文件(只是一个没有文本和 a.odc 扩展名的文本文件)并将连接信息放在连接参数。 You will also probably need to have a Connection parameter if you need to provide a username/password.如果您需要提供用户名/密码,您可能还需要有一个 Connection 参数。 eg例如

Sub c_oledb1()
With ActiveDocument.MailMerge
  .MainDocumentType = wdNotAMergeDocument
  .OpenDataSource Name:="c:\my odcs\empty.odc", _
    connection:="Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Data Source=MYSERVER;Initial Catalog=MYDATABASE", _
    SQLStatement:="SELECT * FROM ""MYTABLE"""
End With
End Sub

For an OLE DB connection, before.odc files there was a much simpler.udl file.对于 OLE DB 连接,before.odc 文件有一个更简单的.udl 文件。 But.odc is probably a better bet these days.但是.odc 这些天可能是一个更好的选择。

Finally, it is a while since I had to do this "for real".最后,我不得不“真正地”做这件事已经有一段时间了。 One of the things I remember is that making a connection to a Server without using a Trusted Connection could be much more problematic, but I cannot remember the details now.我记得的一件事是在使用可信连接的情况下连接到服务器可能会出现更多问题,但我现在不记得细节了。

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

相关问题 将所有数据移至新的MS SQL Server的最简单方法是什么? - What is the easiest way to move all data to a new MS SQL Server? MS SQL:用SSMS创建链接服务器最简单/最好的方法是什么? - MS SQL: What is the easiest/nicest way to create a linked server with SSMS? 使用T-SQL / MS-SQL将字符串附加到现有表格单元格的最简单方法是什么? - What is the easiest way using T-SQL / MS-SQL to append a string to existing table cells? 将MS Access中的VBA代码转换为SQL Server - Convert VBA code in MS Access to SQL server 使用.NET将单个记录写入MS SQL 2008 Server的最有效方法是什么? - What's the most efficient way to write a single record to an MS SQL 2008 Server using .NET? 在MS SQL Server中管理大量表的最佳方法是什么? - What's the best way to manage a large number of tables in MS SQL Server? 使用ms sql server“replace”替换整个单词 - Replace whole word using ms sql server “replace” 使用MS Sql Server 2005区分两个数据库备份文件的最佳方法是什么? - What's the best way to diff two database backup files with MS Sql Server 2005? MS SQL 服务器上 Oracle 的 number(2, 4) 的最佳等效项是什么? - What's the best equivalent for number(2, 4) from Oracle on the MS SQL server? 最简单的部署(非 Web) - SQL Server 还是 MS Access MDB? - Easiest Deployment (non web) - SQL Server or MS Access MDB?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM