簡體   English   中英

通過 Excel VBA,打開 Word 文檔以完成郵件合並。 有沒有辦法自動將 Word Doc Source 設置為等於 Excel 電子表格?

[英]Via Excel VBA, opening Word Document to Complete Mail-merge. Is there way to Automatically set Word Doc Source equal to Excel Spreadsheet?

有以下 Excel VBA 代碼:

  1. 創建 Word 對象,因為我想將我的電子表格鏈接到 Word Mailmerge 模板
  2. 要求用戶指定 Word 模板
  3. 打開 Word 模板(稍后未顯示的代碼會將數據與模板合並到該模板)

挑戰:如果 Word 模板已經“來源”到不同的電子表格(比如上個月的電子表格,它具有不同的名稱),則用戶必須通過這些步驟來選擇我稱之為 Word 的“較新的”電子表格模板來自。

問題:在 Excel VBA(或其他)中有沒有辦法打開 word doc 以便將源更改為當前電子表格?

Set wd = GetObject(, "Word.Application")
If wd Is Nothing Then
    Set wd = CreateObject("Word.Application")
End If

Dim Letter_File As FileDialog
Set Letter_File = Application.FileDialog(msoFileDialogFilePicker)
With Letter_File
    .Filters.Clear
    .AllowMultiSelect = False
    .InitialFileName = "\\Nasprod-5\gbop\Customer Service\RMDs\Process Improvements\"
    If .Show = -1 Then
        Fileaddress = .SelectedItems(1)
    Else
        Exit Sub
    End If
End With

If MsgBox(Fileaddress, vbOKCancel) = vbCancel Then
    MsgBox ("Canceled")
    Exit Sub
End If

Set wdocSource = wd.Documents.Open(Fileaddress)

以下是我在 Word vba 中使用的代碼。

Dim strFileName As String
strFileName = WorkGroupPath & "Parts\Merge Data\Clients_Merge.xlsm"
'
'   Attach Merge list
With ActiveDocument.MailMerge
    .MainDocumentType = wdFormLetters
    .OpenDataSource Name:=strFileName, _
                    SQLStatement:="SELECT * FROM `Clients$`"    ', _
                                                                '
    '       Show merge data
    .ViewMailMergeFieldCodes = False
End With

'   Find client
Application.Dialogs(wdDialogMailMergeFindRecipient).Show

這是在打開/創建主合並文檔時運行的。 您可以將數據源的長名稱分配給 strFilename。

您可能需要將 With 更改為:

With wd.ActiveDocument.MailMerge

以下來自在 Word 中記錄 MailMerge。

    .OpenDataSource Name:=strFileName, _
                    SQLStatement:="SELECT * FROM `Clients$`"    ', _

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM