Excel宏mailmerge - 导出为pdf

时间:2015-10-30 13:34:45

标签: excel vba pdf export mailmerge

我正在使用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

2 个答案:

答案 0 :(得分:2)

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

<div class="content">
   <h2 id="header">This is a long text</h2>
   <p id="inner">This is a text that expands accordling with H2 header other text, other and other...</p>
</div>

现在,您对wd.ActiveDocument.ExportAsFixedFormat PathToSave, 17 'The constant for wdExportFormatPDF 的调用毫无意义,所以我建议将整个Dir(...)If-sentence改为:

FileDialog

编辑:忘记包括&#34; .pdf&#34;扩展

答案 1 :(得分:0)

使用以下代码将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