选择要打印的整张表:Excel VBA

时间:2017-04-06 15:41:04

标签: excel vba excel-vba pdf

我创建了一个VBA宏来将工作簿的特定表格导出为PDF。很简单。我遇到的问题是我的代码只选择了Sheet4的一部分,因此在我的PDF部分中缺少了工作表。

Sheet4包含范围A1:W80中的数据。但是,在运行下面的代码时,仅选择范围A1:W75进行打印。我已确认我的PrintArea包含整个页面。打印时,一切都看起来很棒。

我无休止地寻找解决方案,却没有成功。这可能是页面布局设置问题吗?在导出为PDF时,如何确保选择整个工作表而不是仅选择部分工作表?

这是我的代码:

Sub SaveReportPDF()

    Dim filepath As String

    filepath = "ABC"

    ThisWorkbook.Sheets(Array("Sheet1", "Sheet2", "Sheet3", "Sheet4")).Select
    Selection.ExportAsFixedFormat _
        Type:=xlTypePDF, _
        Filename:=filepath, _
        Quality:=xlQualityStandard, _
        IncludeDocProperties:=True, _
        IgnorePrintAreas:=False, _
        OpenAfterPublish:=False

End Sub

1 个答案:

答案 0 :(得分:3)

作为良好做法,您可以使用以下子设置将每张纸的使用范围设置为打印区域,并使其适合页面:

Sub ScaleForPrinting()
    Dim sh As Worksheet
    ' Stop PrintCommunication for speed
    Application.PrintCommunication = False
    ' Cycle through each sheet
    For Each sh In ThisWorkbook.Sheets(Array("Sheet1", "Sheet2", "Sheet3", "Sheet4"))
        ' Set print area to used range of sheet
        sh.PageSetup.PrintArea = sh.UsedRange
        ' Remove zoom, scale sheet to fit 1 page
        With sh.PageSetup
            .CenterHorizontally = True
            .CenterVertically = True
            .Zoom = False
            .FitToPagesWide = 1
            .FitToPagesTall = 1
        End With
    Next sh
    ' Enable PrintCommunication to apply settings
    Application.PrintCommunication = True
End Sub

然后,您需要在选择后使用ActiveSheet对象,而不是Selection对象。这可能违反直觉,但您希望打印而不是您在表单中选择的

所以:

ScaleForPrinting
ThisWorkbook.Sheets(Array("Sheet1", "Sheet2", "Sheet3", "Sheet4")).Select
ActiveSheet.ExportAsFixedFormat _
    Type:=xlTypePDF, _
    Filename:=filepath, _
    Quality:=xlQualityStandard, _
    IncludeDocProperties:=True, _
    IgnorePrintAreas:=False, _
    OpenAfterPublish:=False
' Deselect sheets to avoid nasty multiple sheet accidental editing!
ThisWorkbook.Sheets("Sheet1").Select