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