Excel 宏邮件合并 - 导出为 pdf

Excel macro mailmerge - export to pdf

我正在使用 vba 宏,它工作得很好,但我需要将文档另存为 .pdf。

我正在寻找提示,但我不知道如何找到它们。上次我找到这个解决方案时:vba mail merge save as pdf 但我不知道将其应用于我的宏。

这是我的代码:

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(ThisWorkbook.Path & "\" & "ArtSpecDatabase.docx")

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

wdocSource.MailMerge.MainDocumentType = wdFormLetters

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

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

Dim PathToSave As String
PathToSave = ThisWorkbook.Path & "\" & "pdf" & "\" & Sheets("Sheet2").Range("B2").Value2 & ".docx"
If Dir(PathToSave, 0) <> vbNullString Then
    wd.FileDialog(FileDialogType:=msoFileDialogSaveAs).Show
Else
    wd.activedocument.SaveAs2 PathToSave, wdFormatDocumentDefault

End If

wd.Visible = True
wdocSource.Close savechanges:=False
wd.activedocument.Close savechanges:=False

Set wdocSource = Nothing
Set wd = Nothing


End Sub

要将 Word 文档导出为 PDF,您需要使用 ExportAsFixedFormat 方法。例如,您可以将 SaveAs2 调用替换为:

wd.ActiveDocument.ExportAsFixedFormat PathToSave, 17 'The constant for wdExportFormatPDF

现在,您对 FileDialog 的调用毫无意义,因此我建议将整个 Dir(...) If 语句更改为:

Dim PathToSave As String
PathToSave = ThisWorkbook.Path & "\" & "pdf" & "\" & Sheets("Sheet2").Range("B2").Value2 & ".pdf"
If Dir(PathToSave, 0) <> vbNullString Then
    With wd.FileDialog(FileDialogType:=msoFileDialogSaveAs)
        If .Show = True Then
            PathToSave = .SelectedItems(1)
        End If
    End With
End If

wd.ActiveDocument.ExportAsFixedFormat PathToSave, 17 'The constant for wdExportFormatPDF

编辑:忘记包含“.pdf”扩展名。

使用以下代码将 excel 导出为 pdf

Sub tst1()

Dim fFilename     As String

    fFilename = "C:\Documents and Settings\test.xlsx"

    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
     fFilename & ".pdf" _
    , Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
    :=False, OpenAfterPublish:=False


End Sub