Print and Preview
Use the PrintOut or PrintPreview method to print or preview objects from code. These objects can print:
Charts,ChartRangeSheets,Worksheets,WorksheetWindowWorkbook
The syntax and arguments for PrintOut and PrintPreview are the same for all objects, so see the Workbook object reference section in Chapter 8 for that information. These methods also apply to the current selection; for instance, the following code previews and prints the selected range:
Sub PrintSelection( )
' Print with preview
Selection.PrintOut , , , True
End SubTip
In my sample code, I set the Preview argument to True so you can see what will print without wasting paper. Simply click Close on the preview window to cancel printing.
You can turn printing on or off for some objects embedded on a worksheet using the PrintObject property. The following code prints a worksheet but omits any embedded controls or other OLE objects:
Sub PrintWithOutObjects( )
Dim ws As Worksheet
Set ws = ActiveSheet
' Prevent printing of controls.
ws.OLEObjects.PrintObject = False
' Print with preview.
ws.PrintOut , , , True
' Restore printing for controls.
ws.OLEObjects.PrintObject = True
End SubYou can further control printing through the Workbook object’s BeforePrint event. For instance, this code prevents the user from printing any part of the workbook:
' ThisWorkbook module ' Cancel print jobs before they are processed. Private Sub Workbook_BeforePrint(Cancel As Boolean) Cancel = True ' Display a message ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access