执行Word邮件合并 [英] Executing Word Mail Merge

查看:162
本文介绍了执行Word邮件合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个excel表与数据,并希望将其导出到一个新的单词文档。

解决方案

可以从excel宏开始 MAIL MERGE / div>

如果您的Word文档已经配置了合并字段,并且您正在从包含要合并到Word文档的数据的工作簿中运行宏,请尝试:

  Sub RunMerge()

Dim wd As Object
Dim wdocSource As Object

Dim strWorkbookName As String

On Error Resume Next
设置wd = GetObject(,Word.Application)
如果wd是Nothing然后
设置wd = CreateObject( Word.Application)
End If
On Error GoTo 0

设置wdocSource = wd.Documents.Open(c:\test\WordMerge.docx)

strWorkbookName = ThisWorkbook.Path& \& ThisWorkbook.Name

wdocSource.MailMerge.MainDocumentType = wdFormLetters

wdocSource.MailMerge.OpenDataSource _
名称:= strWorkbookName,_
AddToRecentFiles:= False ,_
Revert:= False,_
格式:= wdOpenFormatAuto,_
连接:=Data Source =& strWorkbookName& ; Mode = Read,_
SQLStatement:=SELECT * FROMSheet1 $`

使用wdocSource.MailMerge
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
With .DataSource
.FirstRecord = wdDefaultFirstRecord
.LastRecord = wdDefaultLastRecord
End with
.Execute暂停:= False
结束

wd.Visible = True
wdocSource.Close SaveChanges:= False

设置wdocSource =没有
设置wd =没有

结束Sub


I have an excel sheet with data and want to export it to a new word document. Is it possible to start MAIL MERGE from excel macro by clicking a button on the sheet?

解决方案

If your Word document is already configured with the merge fields, and you are running the macro from the workbook that contains the data you want to merge into the Word document, then try this:

Sub RunMerge()

    Dim wd As Object
    Dim wdocSource As Object

    Dim strWorkbookName As String

    On Error Resume Next
    Set wd = GetObject(, "Word.Application")
    If wd Is Nothing Then
        Set wd = CreateObject("Word.Application")
    End If
    On Error GoTo 0

    Set wdocSource = wd.Documents.Open("c:\test\WordMerge.docx")

    strWorkbookName = ThisWorkbook.Path & "\" & ThisWorkbook.Name

    wdocSource.MailMerge.MainDocumentType = wdFormLetters

    wdocSource.MailMerge.OpenDataSource _
            Name:=strWorkbookName, _
            AddToRecentFiles:=False, _
            Revert:=False, _
            Format:=wdOpenFormatAuto, _
            Connection:="Data Source=" & strWorkbookName & ";Mode=Read", _
            SQLStatement:="SELECT * FROM `Sheet1$`"

    With wdocSource.MailMerge
        .Destination = wdSendToNewDocument
        .SuppressBlankLines = True
        With .DataSource
            .FirstRecord = wdDefaultFirstRecord
            .LastRecord = wdDefaultLastRecord
        End With
        .Execute Pause:=False
    End With

    wd.Visible = True
    wdocSource.Close SaveChanges:=False

    Set wdocSource = Nothing
    Set wd = Nothing

End Sub

这篇关于执行Word邮件合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆