简体   繁体   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?

Have the below Excel VBA Code:有以下 Excel VBA 代码:

  1. Creates Word Object since I want to link my spreadsheet to a Word Mailmerge template创建 Word 对象,因为我想将我的电子表格链接到 Word Mailmerge 模板
  2. Asks the user to specify the Word Template要求用户指定 Word 模板
  3. Opens the Word Template (to which later code not displayed merges the data with the template)打开 Word 模板(稍后未显示的代码会将数据与模板合并到该模板)

Challenge: if the Word Template is already "sourced" to a different spreadsheet (say the spreadsheet from last month which has a different name), the user has to go through the steps to select the "newer" spreadsheet which I am calling the Word Template from.挑战:如果 Word 模板已经“来源”到不同的电子表格(比如上个月的电子表格,它具有不同的名称),则用户必须通过这些步骤来选择我称之为 Word 的“较新的”电子表格模板来自。

Question: is there a way within the Excel VBA (or other) to open the word doc so that the source is changed to the current spreadsheet?问题:在 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)

The following is code I use in Word vba.以下是我在 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

This is run upon opening/creating the primary merge document.这是在打开/创建主合并文档时运行的。 You could assign the long name of your data source to strFilename.您可以将数据源的长名称分配给 strFilename。

You might have to change the With to:您可能需要将 With 更改为:

With wd.ActiveDocument.MailMerge

The following came from recording a MailMerge in Word.以下来自在 Word 中记录 MailMerge。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM