Forum Discussion
VBA Script to Print Selected Content in Excel
Sorry, couldn't load the origin file, but here is the screen shot to represent the file. The selected range means from cell A1 to B37, but the range is really depending on the user's selection which means it will be a dynamic range. The version of Excel if Microsoft 365 (Enterprise) and OS is Windows 10 (10.0.19045) Enterprise. Physical memory is 16G. Hopefully this helps for debugging. Thanks.
The setup of the print settings and margin settings are correct.
Here is an example of how you can modify if statement to check if the selected range fits on one page:
Sub PrintWorkbookToPDF()
' Store the current selection range
Dim selectedRange As Range
Set selectedRange = Selection
' Set print settings
With ActiveSheet.PageSetup
.PaperSize = xlPaperLetter ' Set paper size to 8.5x11 inches
.PrintQuality = 2400 ' Set print quality to 2400 dpi
.CenterHorizontally = True ' Center horizontally on page
.CenterVertically = True ' Center vertically on page
.LeftHeader = "" ' Set header to blank
.RightHeader = "" ' Remove right header
.LeftFooter = "" ' Remove left footer
.RightFooter = "" ' Remove right footer
.Orientation = xlLandscape ' Set orientation to landscape
' Set margin settings to normal
.TopMargin = Application.InchesToPoints(0.75)
.BottomMargin = Application.InchesToPoints(0.75)
.LeftMargin = Application.InchesToPoints(0.75)
.RightMargin = Application.InchesToPoints(0.75)
.HeaderMargin = Application.InchesToPoints(0.5)
.FooterMargin = Application.InchesToPoints(0.5)
' Set the print area to the selected range
.PrintArea = selectedRange.Address
' Check if the selected range fits on one page
Dim printableHeight As Double
Dim printableWidth As Double
printableHeight = .PaperHeight - .TopMargin - .BottomMargin
printableWidth = .PaperWidth - .LeftMargin - .RightMargin
If selectedRange.Height <= printableHeight And selectedRange.Width <= printableWidth Then
' If the selected range fits on one page, use the default settings
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = 1
Else
' If the selected range doesn't fit on one page, adjust the content's scale to fit on one page
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = False ' Remove this line to let the content scale vertically as necessary
End If
End With
' Prompt the user to select the folder and enter the file name
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select Folder to Save PDF"
If .Show = -1 Then
' Get the selected folder path
folderPath = .SelectedItems(1)
' Prompt the user to enter the file name
Filename = InputBox("Enter the File Name", "Save PDF")
' Save the workbook as PDF
filePath = folderPath & "\" & Filename & ".pdf"
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=filePath, Quality:=xlQualityStandard
MsgBox "PDF file saved successfully."
Else
MsgBox "No folder selected. PDF file not saved."
End If
End With
End Sub
I hope that works, otherwise I am at my wits end.
- lj4028aimJan 22, 2024Copper ContributorIt seems it could be a good example giving to AI or Copilot to resolve in the near future.
- BeregornJan 22, 2024Copper ContributorSadly, I have found only a little more than the equivalent of "sucks to be you": the "best" suggestion is to manually build a case selector where you read the name of the standard and associate to it their actual measurements. If the format is "custom", you are screwed.
For our particular case, since we set the page size using the PageSetup, you don't really have to read the page size, since you already know it: you just have to replace the .PaperWidth call with the actual number.
Or use the function FitToPage___ = 1 instead of the zoom. - lj4028aimJan 20, 2024Copper ContributorMuch appreciated! I will give it a shot and give it back to you!
- djclementsJan 20, 2024Silver Contributor
lj4028aim In the Page Setup UI dialog box, "Scaling" is an option between "Adjust to" and "Fit to", meaning it's one or the other. If you select "Adjust to" 100% normal size, for example, the "Fit to" settings are ignored. If you select "Fit to" 1 page wide by 1 tall, the zoom percentage is adjusted automatically.
In VBA, to use the "Adjust to" option, simply set the Zoom property to a numeric value for the desired percentage. For example:
'Adjust to: 100% normal size With ActiveSheet.PageSetup .PrintArea = Selection.Address .Zoom = 100 End With
To use the "Fit to" option, first set the Zoom property to False, then set the FitToPagesWide and FitToPagesTall properties as desired. For example:
'Fit to: 1 page wide by 1 tall With ActiveSheet.PageSetup .PrintArea = Selection.Address .Zoom = False .FitToPagesWide = 1 .FitToPagesTall = 1 End With
When using the "Fit to" option, there is no need to calculate the zoom percentage... as soon as you print, print preview or save as PDF, the zoom percentage will automatically adjust for the print area to fit on one page.
I hope that helps clear things up. Cheers!
- BeregornJan 19, 2024Copper Contributor
According to the official documentation, Excel PageSetup doesn't have the properties PaperHeight and PaperWidth; they are listed as properties for the Printer object in Publisher and for the Document object in Visio, and there is a PageHeight property for the PageSetup object in Word and Publisher, but that's it. Apparently there is no way to know what are the sizes of the page in Excel, only if it is custom or one of the standard presets; I've found people asking this exact question on StackOverflow since 2009...
- lj4028aimJun 13, 2023Copper ContributorNikolinoDE
I really appreciate your help and time. Unfortunately, the same error occurs again at line of code "printableHeight = .PaperHeight - .TopMargin - .BottomMargin". I might need to dive deeper into Microsoft manual for VBA to resolve this issue. Again, thanks.