Friday, June 15, 2018

Save an Excel file as a PDF using VBA

In this example, I'm opening an Excel workbook from another Office program (such as Access) and saving the workbook as a PDF:

    Dim xlApp As Excel.Application
    Dim xlWB As Excel.Workbook
    Dim xlWS As Excel.Worksheet        

    Set xlApp = CreateObject("Excel.Application")
    Set xlWB = xlApp.Workbooks.Open("template.xlsx", , False)
    Set xlWS = xlWB.Sheets(1)
    xlWS.Activate          

    With xlWS
        filePathAndName = curPath & "\Reports\ReportName.pdf"
             
        .PageSetup.FitToPagesTall = 1
        .PageSetup.FitToPagesWide = 1

        .ExportAsFixedFormat _
        Type:=xlTypePDF, _
        FileName:=
filePathAndName, _
        Quality:=xlQualityStandard, _
        IncludeDocProperties:=True, _
        IgnorePrintAreas:=False, _
        OpenAfterPublish:=False
    End With

    xlWB.Close
    Set xlWB = Nothing
    Set xlWS = Nothing
    xlApp.Quit
    Set xlApp = Nothing

No comments:

Post a Comment