从数据库中生成各种Word文档并进行合并是一种常见的实践。大多数VBA开发者对此都很熟悉。在本文中,将展示如何通过执行TransactSQL语句从数据库表中获取记录,并将所有记录合并到一个文档中。
这是一种非常简便的方法。只需要对以下方法有一个基本的了解:
MailMerge.OpenDataSource 方法:将数据源附加到指定的文档,如果它还不是主文档的话。
VBScript 示例:
Public Sub MergeDocument(strDocumentPath As String, _
strDocumentFile As String, _
strSQLStatement As String)
On Error GoTo ErrorHandler
Dim ObjApplication As Word.Application
Dim ObjDocument As Word.Document
DoEvents
Dim strSourceName As String
Dim MergeSubType As WdMergeSubType
strSourceName = "C:\MyDatabase.mdb"
MergeSubType = wdMergeSubTypeWord2000
Set ObjDocument = GetObject(strDocumentPath & strDocumentFile, "Word.Document")
ObjDocument.Application.Visible = True
DoEvents
ObjDocument.MailMerge.OpenDataSource Name:=strSourceName, _
SQLStatement:=strSQLStatement
DoEvents
With ObjDocument.MailMerge
.Destination = wdSendToNewDocument
.Execute Pause:=True
End With
DoEvents
ObjDocument.Close wdDoNotSaveChanges
Set ObjDocument = Nothing
Set ObjApplication = Nothing
Exit_mergeDocument:
Exit Sub
ErrorHandler:
MsgBox Err.Description
Resume Exit_mergeDocument
End Sub