How to save excel specific page to pdf?

Asked by At

I am trying to add a button where the button prompts user to enter a page number and save that specific page to pdf.

Here is the code that I use to save as pdf. But this saves whole worksheet to pdf.

Option Explicit

Sub SaveAsPDF()

Dim wsA As Worksheet
Dim wbA As Workbook
Dim strTime As String
Dim strName As String
Dim strPath As String
Dim strFile As String
Dim strPathFile As String
Dim myFile As Variant
Dim Filename As String

On Error GoTo errHandler

Set wbA = ActiveWorkbook
Set wsA = ActiveSheet
strTime = Format(Now(), "yyyymmdd\_hhmm")

Filename = ActiveWorkbook.Name                          '<------- added this code
If InStr(Filename, ".") > 0 Then
   Filename = Left(Filename, InStr(Filename, ".") - 1)
End If

'get active workbook folder, if saved
strPath = wbA.Path
If strPath = "" Then
  strPath = Application.DefaultFilePath
End If
strPath = strPath & "\"

'replace spaces and periods in sheet name
strName = Replace(Filename, " ", "_")                    '<--- changed wbA to Filename
strName = Replace(strName, ".", "_")

'create default name for savng file
strFile = strName & ".pdf"
strPathFile = strPath & strFile

'use can enter name and
' select folder for file
myFile = Application.GetSaveAsFilename _
    (InitialFileName:=strPathFile, _
        FileFilter:="PDF Files (*.pdf), *.pdf", _
        Title:="Select Folder and File Name to save")

'export to PDF if a folder was selected
If myFile <> "False" Then
    wsA.ExportAsFixedFormat _
        Type:=xlTypePDF, _
        Filename:=myFile, _
        Quality:=xlQualityStandard, _
        IncludeDocProperties:=True, _
        IgnorePrintAreas:=False, _
    'confirmation message with file info
    MsgBox "PDF file has been saved."
End If

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

End Sub

What are the changes that I need to bring to let user to save a specific page to pdf. And by the way I save all these codes on personal.xlb file.

I would appreciate if someone helps with an answer. Thank you.

0 Answers