Program with Permissions

Microsoft provides the permissions objects through the Office object library since permissions can be applied to Excel, Word, and PowerPoint documents. Figure 26-18 illustrates the hierarchy of the permission objects.

Office permission object model

Figure 26-18. Office permission object model

You must have Rights Management credentials installed before you can set permissions on a document. Otherwise, most permission methods will cause runtime errors. See the preceding section for instructions on how to install credentials.

Once credentials are installed, you can restrict access to workbooks by setting the Permission collection’s Enabled property to True, as shown here:

    Dim irm As Office.Permission
    Set irm = ThisWorkbook.Permission
    irm.Enabled = True

The preceding code sets the workbook as Do Not Distribute. You are given full control, but no other users have permissions. Use the Add method to add permissions for other users. You must add each user individually, even if all have the same permissions, as shown here:

    Set irm = ThisWorkbook.Permission
    irm.Add "ExcelDemo@hotmail.com", MsoPermission.msoPermissionView
    irm.Add "someone@microsoft.com", MsoPermission.msoPermissionView

Use Or to combine permissions for a user. For example, the following code allows to read, print, and copy a workbook:

 irm.Add "someone@microsoft.com", MsoPermission.msoPermissionView Or & _ MsoPermission.msoPermissionPrint ...

Get Programming Excel with VBA and .NET now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.