我正在使用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
您好,感谢您的更新。我已将您的代码放到我的宏中,但它不会运行。我得到运行时错误'5:无效的过程调用或参数。调试后,这个错误,它显示我在代码行中的错误: 'wd.ActiveDocument.ExportAsFixedFormat PathToSave,wdExportFormatPDF' 你能帮我什么错? – Jean
尝试用17替换'wdExportFormatPDF'。 – DanL
太棒了!!!谢谢。现在它运行;) – Jean