2010-07-30 56 views
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 

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

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

+1

当然objWord.ActiveDocument.SaveAs? – Fionnuala 2010-07-30 14:20:37

+0

我是一个工具,并假定ActiveDocument将是一个objWord的方法...不是一些其他的随机对象。谢谢 – Mervyn 2010-07-30 14:58:34

+2

可能你认为是因为你从Word复制了代码。换言之,应用程序是.ActiveDocument的默认父项。当运行相同的代码时,objWord对象变量是父代,因为它代表了Word应用程序。因此,由于任何未加前缀的命令都可能是Application对象的子对象,因此将代码转换为Access时,所有代码均以表示Word应用程序对象的对象变量为前缀。 – 2010-07-30 18:12:27

回答

1

将ActiveDocument更改为objWord.ActiveDocument。达到预期的结果。

感谢Remou。

+0

欢迎您:) – Fionnuala 2010-07-30 15:20:50

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