2015-10-30 120 views
1

我正在使用vba宏,它完美地工作,但我需要将文档另存为.pdf。Excel宏mailmerge - 导出为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

导出Word文档为PDF格式,你需要使用ExportAsFixedFormat方法。例如,你可以用这个替换您的通话SaveAs2:

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

现在,你对FileDialog通话是没有意义的,所以我建议改变整个迪尔(...)如果用一句话来这样的:

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”扩展名。

+0

您好,感谢您的更新。我已将您的代码放到我的宏中,但它不会运行。我得到运行时错误'5:无效的过程调用或参数。调试后,这个错误,它显示我在代码行中的错误: 'wd.ActiveDocument.ExportAsFixedFormat PathToSave,wdExportFormatPDF' 你能帮我什么错? – Jean

+0

尝试用17替换'wdExportFormatPDF'。 – DanL

+0

太棒了!!!谢谢。现在它运行;) – Jean

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