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:
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:
- Create an excel addin project.
- Initialize WorkbookBeforePrint delegate.
- this.Application.WorkbookBeforePrint += BeforePrint;
- Set the Cancel parameter to true at the end as in the following code snippet to block the event.
- private void BeforePrint(Excel.Workbook wb, ref bool Cancel)
- {
- Excel.Worksheet sheet = wb.Sheets[1];
-
-
- Excel.Range range = sheet.Range["A1", "B2"];
-
- int rows = range.Rows.Count;
- int columns = range.Columns.Count;
-
-
-
- MessageBox.Show(@"Sensitive data => Printing Cancelled");
-
- this.Application.StatusBar = "Printing Cancelled";
-
- Cancel = true;
- }
I have attached the project for your reference.