1

我想使用宏从同一个 Excel 工作簿运行邮件合并。

我需要使用 DDE 作为数据源,因为我想保留格式。

这个宏永远运行并最终冻结我的屏幕。

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("P:\trial.docx")

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

    wdocSource.Mailmerge.MainDocumentType = wdFormLetters

    wdocSource.Mailmerge.OpenDataSource _
            Name:=strWorkbookName, _
            SubType:=wdMergeSubTypeWord2000, _
            AddToRecentFiles:=False, _
            Revert:=False, _
            Format:=wdOpenFormatAuto, _
            Connection:=`Sheet1$` & ";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

4

0 回答 0