Cancel Printing Operation On A Workbook In Excel

In this article you will learn how to cancel printing operation on a Workbook in Excel.

Printing a worksheet or a workbook can be controlled using Excel event model. When a sheet or workbook contains some sensitive data, you can either completely disallow printing or hide the sensitive data before the workbook gets printed.

In this article, I shall assume if a sheet contains sensitive or classified data, the complete workbook is also classified. That means, I would completely block the printing event and show user message that printing is cancelled and at the same time change the Excel status bar as in the following screenshot:

Excel sheet

In order to achieve the said behavior, one should intercept printing event from Excel event model and set the required parameter to block it. In between, user can do the preparation if any data should be hidden, but in my case, I shall skip this functionality.

Let’s follow the step:

  1. Create an excel addin project.

  2. Initialize WorkbookBeforePrint delegate.
    1. this.Application.WorkbookBeforePrint += BeforePrint;  
  3. Set the Cancel parameter to true at the end as in the following code snippet to block the event.
    1. private void BeforePrint(Excel.Workbook wb, ref bool Cancel)  
    2. {  
    3.    Excel.Worksheet sheet = wb.Sheets[1];  
    4.   
    5.    //read a specified range  
    6.    Excel.Range range = sheet.Range["A1""B2"];  
    7.   
    8.    int rows = range.Rows.Count;  
    9.    int columns = range.Columns.Count;  
    10.   
    11.   
    12.    //show user a message   
    13.    MessageBox.Show(@"Sensitive data => Printing Cancelled");  
    14.    //set the application status  
    15.    this.Application.StatusBar = "Printing Cancelled";  
    16.    //cancel the event  
    17.    Cancel = true;  
    18. }  

I have attached the project for your reference.