Excelmacrosmailmerge – 导出为pdf

我正在工作的VBAmacros,它完美的作品,但我需要保存为.pdf文件。

我正在寻找提示,但我不知道如何find它们。 上次我发现这个解决scheme: vba邮件合并保存为pdf,但我不知道应用到我的macros。

这是我的代码:

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 

要将PDF文档导出为PDF,您需要使用ExportAsFixedFormat方法。 例如,你可以用这个replace你的SaveAs2调用:

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

现在,你调用FileDialog没有任何意义,所以我build议将整个Dir(…)If-sentence改为:

 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