2

我正在尝试从访问中打开文档,执行邮件合并,然后使用 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

我得到了合并的文档,但是我无法保存它。我收到一条错误消息,指出没有打开文档时无法执行该命令。

如果有人可以提供任何建议,将不胜感激。

4

2 回答 2

1

将 ActiveDocument 更改为 objWord.ActiveDocument。最终得到了想要的结果。

谢谢雷穆。

于 2010-07-30T15:00:31.327 回答
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
于 2010-07-30T14:49:42.770 回答