a_dzik
a_dzik

Reputation: 977

Excel pdf export

I'm new in Excel macros. I try to make a "save as pdf" button. I wrote a code like this:

Sub save_as_pdf()
'
' save_as_pdf Macro
' Saves sheet as PDF
'
Dim Path As String
Dim filename As String
Path = "/Users/Adrian/Desktop/"
filename = ThisWorkbook.Sheets("Controller").Range("B20")
PathAndFilename = Path & filename & ".pdf"
MsgBox "Saved file as: " & PathAndFilename

Sheets("View").Select
Application.DisplayAlerts = False
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, filename:= _
   PathAndFilename, Quality:=xlQualityMinimum, _
   IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
   False

Application.DisplayAlerts = True

End Sub

I need the Range("B20") because I keep there a filename based on some in-excel logic. The MsgBox produces a valid path and filename.

Yet, when I run this I get a "Error while printing" and a "Runtime error 1004" highlighting ActiveSheet.ExportAsFixedFormat ...

Upvotes: 0

Views: 206

Answers (1)

QHarr
QHarr

Reputation: 84465

Set a print area in the sheet to export.

Also verify path as I expected \ and a drive letter e.g. C:\

The following works for me

Option Explicit

Sub save_as_pdf()

    Dim Path As String
    Dim filename As String
    Dim PathAndFileName As String

    Path = "C:\Users\User\Desktop\" ' "C:\Users\Adrian\Desktop\"
    filename = ThisWorkbook.Sheets("Controller").Range("B20")
    PathAndFileName = Path & filename & ".pdf"
    MsgBox "Saved file as: " & PathAndFileName

    Sheets("View").Select
    Application.DisplayAlerts = False
    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, filename:= _
                                    PathAndFileName, Quality:=xlQualityMinimum, _
                                    IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
                                    False

    Application.DisplayAlerts = True

End Sub

Upvotes: 1

Related Questions