2010-07-30 59 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