使用VBA将Excel表格循环中的单元格范围导出到多页PDF

时间:2015-06-02 13:29:56

标签: excel vba excel-vba pdf export

我正在尝试使用以下内容将特定范围从Excel工作表导出到pdf文件:

Sub pdfpls()
Dim pdfName As String
Dim fileSaveName As String

pdfName = cb_sn.Value & "_report_" & cb_year.Value & ".pdf"
ChDir ThisWorkbook.Path
fileSaveName = Application.GetSaveAsFilename(pdfName, _
fileFilter:="PDF Files (*.pdf), *.pdf")
If fileSaveName <> False Then
Sheet12.Range(Cells(1, 1), Cells(43, 9)).ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
    fileSaveName _
    , Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
    :=False, OpenAfterPublish:=False
End If
End Sub  

然而,运行它会导致运行时错误“13”不匹配错误。 理想情况下,我想要两个按钮,一个只打印一个报告,另一个(稍微不同的代码),可以将多个报告打印成一个pdf。甚至无法让单一报告发挥作用。仅供参考,cb_sn和cb_year是报告的序列号和年份的组合框,如果重要的话,我正在使用excel 2007。所有帮助表示赞赏!谢谢!

卡尔文

编辑:

我发现其他一些代码可以很好地制作单个pdf,但是我无法循环代码,因此它将每个序列号的页面添加到pdf文件中。即我想要一个100页的pdf,其中每个页面是不同序列的报告。以下是用于将一次运行保存为pdf的新代码:

Sub print1pdf()

Dim ws As Worksheet
Dim strPath As String
Dim myFile As Variant
Dim strFile As String
On Error GoTo errHandler

Set ws = ActiveSheet

'enter name and select folder for file
' start in current workbook folder
strFile = Replace(Replace(ws.Name, " ", ""), ".", "_") _
        & "_" & Sheet1.cb_sn & "_" _
        & Sheet1.cb_year _
        & ".pdf"
strFile = ThisWorkbook.Path & "\" & strFile

myFile = Application.GetSaveAsFilename _
(InitialFileName:=strFile, _
    fileFilter:="PDF Files (*.pdf), *.pdf", _
    Title:="Select Folder and FileName to save")

If myFile <> "False" Then
ws.Range(Cells(1, 1), Cells(43, 9)).ExportAsFixedFormat _
    Type:=xlTypePDF, _
    FileName:=myFile, _
    Quality:=xlQualityStandard, _
    IncludeDocProperties:=True, _
    IgnorePrintAreas:=False, _
    OpenAfterPublish:=False

'MsgBox "PDF file has been created."
End If

exitHandler:
Exit Sub
errHandler:
MsgBox "Could not create PDF file"
Resume exitHandler

0 个答案:

没有答案