excel - 通过 Excel VBA,打开 Word 文档以完成邮件合并。有没有办法自动设置 Word Doc Source 等于 Excel 电子表格?
问题描述
有以下 Excel VBA 代码:
- 创建 Word 对象,因为我想将电子表格链接到 Word Mailmerge 模板
- 要求用户指定 Word 模板
- 打开 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)
解决方案
The following is code I use in 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.
You might have to change the With to:
With wd.ActiveDocument.MailMerge
The following came from recording a MailMerge in Word.
.OpenDataSource Name:=strFileName, _
SQLStatement:="SELECT * FROM `Clients$`" ', _
推荐阅读
- javascript - 在 Angular 中设置 Angular Web 组件的样式
- javascript - 我正在尝试使用 Sinon 存根和模拟来测试我的函数,但我收到了一个错误。请建议我正确的写作技巧
- caching - 您如何清除 Whatsapp 上 URL 的片段元数据/打开图形缓存?
- javascript - PWA 添加到主屏幕
- python - Odoo 13:代码中的 act_window 操作忽略了 search_view
- python - PyQt5,将变量列表传递给另一个类
- javascript - 在 React.js 中如何将数据从子组件传递到父组件
- javascript - React Firebase 删除操作
- dicom - 在覆盖 DICOM 中的像素数据时,应替换除 UID 之外的哪些 DICOM 标签?
- r - 单击多边形时地图上的条形图弹出不工作大型 SQL Server 数据库查询