Protect Spreadsheet Ranges in Google Apps Script

In a recent post I described how Google have extended the capabilities of range protection in spreadsheets. They’ve also made it possible to protect ranges in Google Apps Script by means of the new Protection class.

Usage is pretty straightforward, and code samples probably serve better than written description. Here’s how to protect a simple range:

// Protect range C1:G10
var ss = SpreadsheetApp.getActive();
var range = ss.getRange('C1:G10');
var protection = range.protect().setDescription('This is now a protected range');

The object stored in the variable I’ve called protection now represents my protected range, and I can manipulate it directly in code.

First want to set up who are the editors for it, starting with myself:

var me = Session.getEffectiveUser();
protection.addEditor(me);

You can find out who the editors are for my protected range using the getEditors() method. Here, I’m using that information to remove all the editors for my protected range:

var eds = protection.getEditors();
protection.removeEditors(eds);

To produce an unprotected range (or ranges) within a protected range is easy too:

var unprotected = sheet.getRange('E2:F3');
protection.setUnprotectedRanges([unprotected]);

Or I can remove the protection altogether:

protection.remove();