我正在尝试从访问中打开文档,执行邮件合并,然后使用VBA从合并中保存文档输出。
这是我目前的尝试:
Dim templateName as String, tempRoot as String
tempRoot = "C:\report\"
templateName = tempRoot & "template.doc"
Dim objDoc As Word.Document
Dim objWord As New Word.Application
Set objDoc = objWord.Documents.Open(templateName)
objWord.Visible = True
exportData "AnnualData", tempRoot & "annualData.txt" 'Outputs query to txt file for merge
objDoc.MailMerge.OpenDataSource NAME:= _
tempRoot & "annualData.txt", ConfirmConversions:=False, ReadOnly _
:=False, LinkToSource:=True, AddToRecentFiles:=False, PasswordDocument:= _
"", PasswordTemplate:="", WritePasswordDocument:="", _
WritePasswordTemplate:="", Revert:=False, Format:=wdOpenFormatAuto, _
Connection:="", SQLStatement:="", SQLStatement1:="", SubType:= _
wdMergeSubTypeOther
objDoc.MailMerge.Execute
objDoc.Close False 'Ideally after closing, the new document becomes the active document?
ActiveDocument.SaveAs tempRoot & "testReport.doc" 'And then save?
Set objWord = Nothing
Set objDoc = Nothing
我收到合并的文件,但是,我无法保存。我收到一条错误,指出在没有文档打开时无法执行该命令。
如果有人可以提供任何建议,我们将不胜感激。
答案 0 :(得分:1)
将ActiveDocument更改为objWord.ActiveDocument。结束了预期的结果。
谢谢Remou。
答案 1 :(得分:0)
我刚刚经历过这个。这就是我正在做的事情并且效果很好。 oDocument是用户通过打开的对话框选择的合并形式。 excel文件是我之前导出并停留在用户临时文件夹中的查询。我尝试使用Access查询和临时表这种技术,但发现使用excel更加麻烦。
Sleep命令来自导入的系统dll函数(Public Declare Sub Sleep Lib“kernel32”(ByVal dwMS As Long))并提供Word时间来运行合并。实际上,这可能就是你所需要的。这是使用Office 2007。
If Not oDocument Is Nothing Then
' get merge source file
Set oFSO = New FileSystemObject
Set oFolder = oFSO.GetSpecialFolder(TemporaryFolder)
strTempFile = oFolder.Path & "\PTDMergeSource.xls"
' run merge
With oDocument.MailMerge
.MainDocumentType = wdFormLetters
.Destination = wdSendToNewDocument
.OpenDataSource strTempFile, WdOpenFormat.wdOpenFormatDocument, False, False, False, False, , , , , , , "SELECT * FROM `tblMerge$`", , False, WdMergeSubType.wdMergeSubTypeAccess
.Execute True
End With
Sleep 2
oDocument.Close False
Else
MsgBox "Action was cancelled, or there was an error opening that document. Please try again, then try opening that document in Word. It may be someone else has locked that document (they are editing it). If the problem persists, email the document to the support contractor."
End If