将表格保存为pdf

时间:2015-04-10 07:11:35

标签: excel vba excel-vba pdf

我在尝试在单个pdf中打印多张纸时遇到此问题。在网上浏览和在论坛中我发现了这段代码,但是当我使用它时,我得到错误9"下标超出范围"而且我不明白为什么。我尝试了一个新的工作簿代码,它正常工作。有人能帮助我吗?

Private Sub cmd_PrintPDF_Click()

ThisWorkbook.Sheets(Array("Costs", "Cars")).Select

Selection.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
ThisWorkbook.Path & "/" & "Cost&Car", Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True

End Sub

这个宏从我的工作簿的主面板运行,其中有各种Command按钮,可以将您引导到请求的工作表中。当我运行此宏时,工作表" Cars"是隐藏的,可能是这个问题?我在代码之前尝试使用.Activate,但它仍然无法正常工作。

2 个答案:

答案 0 :(得分:1)

实际上,您无法打印隐藏的纸张 这是你的代码没有无用的和资源贪婪的Select

Private Sub cmd_PrintPDF_Click()

ThisWorkbook.Sheets("Costs").Visible = True
ThisWorkbook.Sheets("Cars").Visible = True

ThisWorkbook.Sheets(Array("Costs", "Cars")).ExportAsFixedFormat _
    Type:=xlTypePDF, _
    Filename:=ThisWorkbook.Path & "/" & "Cost&Car", _
    Quality:=xlQualityStandard, _
    IncludeDocProperties:=True, _
    IgnorePrintAreas:=False, _
    OpenAfterPublish:=True


ThisWorkbook.Sheets("Costs").Visible = False
ThisWorkbook.Sheets("Cars").Visible = False

End Sub

答案 1 :(得分:1)

我将此代码用于导出工作表到pdf。也许对你有用。

Sub SheetsToPdf()

Dim Arr() As String
Dim PdfFileName As String
PdfFileName = "Cost&Car"

ReDim Arr(1, 1)
'sheets name in 1st column, 2nd column for info about visibility sheets
Arr(0, 0) = "Costs"
Arr(1, 0) = "Cars"

Cells(1, 1).Select
For i = LBound(Arr, 1) To UBound(Arr, 1)

Arr(i, 1) = ThisWorkbook.Sheets(Arr(i, 0)).visible ' info about visibility sheets

If Arr(i, 1) = "0" Then 'check visible Sheets "-1" - visible = True, "0" - visible = False
    ThisWorkbook.Sheets(Arr(i, 0)).visible = True
    OrgVisible = False
End If

If i = 0 Then
ThisWorkbook.Sheets(Arr(i, 0)).Select
Else
ThisWorkbook.Sheets(Arr(i, 0)).Select False 'select all sheets with names in arr()
End If  



Next i

'select all data
Cells.Select

'export to pdf
Selection.ExportAsFixedFormat Type:=xlTypePDF, FileName:= _
ThisWorkbook.path & "/" & PdfFileName, Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True

'restore old visibility for sheets
For i = LBound(Arr, 1) To UBound(Arr, 1)
    If Arr(i, 1) = "0" Then 'set old visible
        ThisWorkbook.Sheets(Arr(i, 0)).visible = False
    End If
Next i

End Sub

也许你需要这个更简单的版本?仅导出可见的工作表:

Sub SheetsToPdf2()

Dim PdfFileName As String
PdfFileName = "Cost&Car"

Cells(1, 1).Select
For Each Sheets_ In Sheets
    If Sheets_.visible Then
    ThisWorkbook.Sheets(Sheets_.Name).Select False
    End If
Next
'select all data in one sheet
Cells.Select

'export to pdf
Selection.ExportAsFixedFormat Type:=xlTypePDF, FileName:= _
ThisWorkbook.path & "/" & PdfFileName, Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True

End Sub