2015-10-30 122 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