Avatar of Maxime Fleury
Maxime Fleury
Flag for Canada asked on

Macro: print each sheet to pdf using ExportAsFixedFormat

Hello,

I got this macro which save the active sheet of a workbook as pdf. I want to add the following function : do it for every sheets of the workbook and at the beginning of the macro i want to add a value with a dialog box which will be added at the beginning of the filename. Exemple : sheet name : 036, 037. Filename : Dialogboxinput-036, Dialogboxinput-037.

Sub PrintSheetsToPDF2()
    pdfName = ActiveSheet.Name
    ChDir ActiveWorkbook.Path & "\"
    fileSaveName = ActiveSheet.Name
   
     ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
        fileSaveName _
        , Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
        :=False, OpenAfterPublish:=False
   
    MsgBox "File Saved " & " " & fileSaveName
End Sub

Regards,
Maxime
Microsoft ExcelVisual Basic Classic

Avatar of undefined
Last Comment
Maxime Fleury

8/22/2022 - Mon
Joe Howard

Please try this:
Sub PrintSheetsToPDF2()
    Dim sht As Worksheet
    Dim fileSaveName As String, strDialogPrefix As String

    For Each sht In ActiveWorkbook.Sheets
        strDialogPrefix = InputBox("Enter prefix for sheet: " & sht.Name, "Export")
        fileSaveName = strDialogPrefix & "-" & sht.Name
        ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
                                        fileSaveName _
                                        , Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
                                                                                                  :=False, OpenAfterPublish:=False
        MsgBox "File Saved " & " " & fileSaveName
    Next
End Sub

Open in new window

Maxime Fleury

ASKER
Hi MacroShadow,

there is 2 problems, first I want the same dialog prefix for every sheets (only 1 input). Also, the macro always save the first sheet for every sheets. The names are correct.
Regards,
Joe Howard

For your first issue use this:
Sub PrintSheetsToPDF2()
    Dim sht As Worksheet
    Dim fileSaveName As String, strDialogPrefix As String

    strDialogPrefix = InputBox("Enter prefix", "Export")

    For Each sht In ActiveWorkbook.Sheets
        fileSaveName = strDialogPrefix & "-" & sht.Name
        ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
                                        fileSaveName _
                                        , Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
                                                                                                  :=False, OpenAfterPublish:=False
        MsgBox "File Saved " & " " & fileSaveName
    Next
End Sub

Open in new window

I didn't understand the second problem.
Your help has saved me hundreds of hours of internet surfing.
fblack61
SOLUTION
Koen

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Joe Howard

Here you go:
Sub PrintSheetsToPDF2()
    Dim sht As Worksheet
    Dim fileSaveName As String, strDialogPrefix As String

    strDialogPrefix = InputBox("Enter prefix", "Export")

    For Each sht In ActiveWorkbook.Sheets
        fileSaveName = strDialogPrefix & "-" & sht.Name
        sht.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
                                        fileSaveName _
                                        , Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
                                                                                                  :=False, OpenAfterPublish:=False
        MsgBox "File Saved " & " " & fileSaveName
    Next
End Sub

Open in new window

Thanks Koen, missed that one.
Maxime Fleury

ASKER
Thanks both of you.
I tested the macro on a new workbook and it worked great. But in my working workbook, the macro stop  with error code 5 saying there is a bad argument. I tested several time with the same result.

The problematic code :
sht.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
                                        fileSaveName _
                                        , Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
                                                                                                  :=False, OpenAfterPublish:=False

I uploaded the file in case you want to test it.
Regards
test.xls
Joe Howard

It's because you have a hidden sheet. To skip hidden sheets use this:
Sub PrintSheetsToPDFFinal()
    Dim sht As Worksheet
    Dim fileSaveName As String, strDialogPrefix As String

    strDialogPrefix = InputBox("Enter prefix", "Export")

    For Each sht In ActiveWorkbook.Sheets
        If sht.Visible = True Then
            fileSaveName = strDialogPrefix & "-" & sht.Name
            sht.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
                                    fileSaveName _
                                    , Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
                                                                                              :=False, OpenAfterPublish:=False
            MsgBox "File Saved " & " " & fileSaveName
        End If
    Next
End Sub

Open in new window

⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Maxime Fleury

ASKER
Good. Thanks. Missed that one. Is there a way to browse the directory to use to save the pdf? Or save the pdf where the .xls file is saved?
ASKER CERTIFIED SOLUTION
Joe Howard

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Joe Howard

To browse for a folder:
Sub PrintSheetsToPDFFinal()
    Dim sht As Worksheet
    Dim fileSaveName As String, strDialogPrefix As String

    strDialogPrefix = InputBox("Enter prefix", "Export")

    For Each sht In ActiveWorkbook.Sheets
        If sht.Visible = True Then
            fileSaveName = BrowseForFolder & "\" & strDialogPrefix & "-" & sht.Name
            sht.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
                                    fileSaveName _
                                    , Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
                                                                                              :=False, OpenAfterPublish:=False
            MsgBox "File Saved " & " " & fileSaveName
        End If
    Next
End Sub


Function BrowseForFolder(Optional OpenAt As Variant) As Variant
'Function purpose:  To Browser for a user selected folder.
'If the "OpenAt" path is provided, open the browser at that directory
'NOTE:  If invalid, it will open at the Desktop level
'Source: http://www.vbaexpress.com/kb/getarticle.php?kb_id=284

    Dim ShellApp As Object

    'Create a file browser window at the default folder
    Set ShellApp = CreateObject("Shell.Application"). _
                   BrowseForFolder(0, "Please choose a folder", 0, OpenAt)

    'Set the folder to that selected.  (On error in case cancelled)
    On Error Resume Next
    BrowseForFolder = ShellApp.self.Path
    On Error GoTo 0

    'Destroy the Shell Application
    Set ShellApp = Nothing

    'Check for invalid or non-entries and send to the Invalid error
    'handler if found
    'Valid selections can begin L: (where L is a letter) or
    '\\ (as in \\servername\sharename.  All others are invalid
    Select Case Mid(BrowseForFolder, 2, 1)
        Case Is = ":"
            If Left(BrowseForFolder, 1) = ":" Then GoTo Invalid
        Case Is = "\"
            If Not Left(BrowseForFolder, 1) = "\" Then GoTo Invalid
        Case Else
            GoTo Invalid
    End Select

    Exit Function

Invalid:
    'If it was determined that the selection was invalid, set to False
    BrowseForFolder = False

End Function

Open in new window

Maxime Fleury

ASKER
Good job!
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes