我正在尝试在 Word 中使用 Visual Basic 自动执行MailMergeDataSource
文档搜索,然后执行MailMerge
。我让两个步骤独立运行。但是,如果我SearchForDocument()
先调用该函数,则ExecuteMerge()
失败。我收到运行时错误“5631”:Word 无法将主文档与数据源合并,因为数据记录为空或没有数据记录与您的查询选项匹配。
我可以运行该SearchForDocument()
函数并记下记录号。然后,如果我关闭 Word 并重新打开而不保存,我就可以ExecuteMerge()
成功调用该记录号。
我尝试将其重置.ActiveRecord
为 1,但没有成功。
此 VB 函数在数据源中搜索匹配项doc_id
,并从数据集中返回记录号。它运行正常,没有明显问题。从数据集中返回准确的记录号。
Function SearchForDocument(doc_id As String)
' Searches datasource for given record id number.
Dim dsMain As MailMergeDataSource
Dim numRecord As Integer
ActiveDocument.MailMerge.ViewMailMergeFieldCodes = False
Set dsMain = ActiveDocument.MailMerge.DataSource
'Initializes at first record because .ActiveRecord method only searches for first match in descending records from current record
dsMain.ActiveRecord = 1
If dsMain.FindRecord(FindText:=doc_id, Field:="SAMPLE") = True Then
numRecord = dsMain.ActiveRecord
Else
MsgBox "Record " & doc_id & " was not found."
numRecord = 0
End If
SearchForDocument = numRecord
End Function
此函数MailMerge
从数据集中给定的记录号执行。除非我SearchForDocument
先运行该函数,否则它会正常工作。当它失败时,我会收到运行时错误“5631”。
Function ExecuteMerge(ByVal TargetRecord As Integer)
Set myMerge = ActiveDocument.MailMerge
If myMerge.State = wdMainAndSourceAndHeader Or _
myMerge.State = wdMainAndDataSource Then
With myMerge.DataSource
.FirstRecord = TargetRecord
.LastRecord = TargetRecord
End With
End If
With myMerge
.Destination = wdSendToNewDocument
.Execute
End With
End Function