Forum Discussion
Jonathan865
Nov 25, 2022Copper Contributor
Excel VBA code to print each sheet individually and rename based on sheet name
Hi all,
Im looking for an excel VBA code to print each sheet individually and rename the pdf based on sheet name.
Any help would be greatly appreciated.
Thanks
- Mark_DekeyserCopper Contributor
Hi Jonathan,
Please have a look at this code.
It iterates through each sheet, prints it and saves it by its name in pdf format.
Let me know if it works for you.
Option Explicit
Sub udsPrintSheetsAndSaveAsPdf()
Dim shtThisSheet As Worksheet
Dim booRC As BooleanApplication.ScreenUpdating = False
booRC = True
For Each shtThisSheet In ActiveWorkbook.Worksheets
Sheets(shtThisSheet.Name).Select
If booRC Then booRC = udfPrintSheet()
If booRC Then booRC = udfSaveAsPdf(shtThisSheet.Name)
Next shtThisSheet
Application.ScreenUpdating = TrueEnd Sub
Function udfPrintSheet() As Boolean
Application.ScreenUpdating = False
With ActiveSheet.PageSetup
.PrintArea = ""
.PrintTitleRows = ""
.PrintTitleColumns = ""
.Orientation = xlPortrait
.PaperSize = xlPaperA4 ' I assume you want to print on A4, if not...
.FitToPagesWide = 1
.FitToPagesTall = 1
End With
Application.PrintCommunication = True
ActiveWindow.SelectedSheets.PrintOut Copies:=1, Collate:=True, _
IgnorePrintAreas:=False
Application.PrintCommunication = False
udfPrintSheet = True
End FunctionFunction udfSaveAsPdf(strSheetName As String) As Boolean
Application.ScreenUpdating = False
Application.DisplayAlerts = FalseChDir "C:\temp" ' I assume you have a C:\temp folder...
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, Filename:="C:\temp\" & strSheetName, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=False
Application.DisplayAlerts = True
udfSaveAsPdf = TrueEnd Function
- Jonathan865Copper Contributor
Thank you for this, but im getting an error for this section:
Sheets(shtThisSheet.Name).Select
Error: "Select method of worksheet class failed"
What should i put to fix it?
Thanks,