I would like to write scripts that can protect and unprotect a range in a Google spreadsheet. The first function works:
function AddProtectionToColumn() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var range = ss.getRange('A:A');
var protectSs = range.protect().setDescription('Protect column A');
var me = Session.getEffectiveUser();
protectSs.addEditor(me);
protectSs.removeEditors(protectSs.getEditors());
if (protectSs.canDomainEdit()) {
protectSs.setDomainEdit(false);
}
}
but the second function is not working:
function RemoveProtectionToColumn() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var range = ss.getRange('A:A');
range.protect().remove();
var me = Session.getEffectiveUser();
protectSs.addEditor(me);
protectSs.removeEditors(protectSs.getEditors());
if (protectSs.canDomainEdit()) {
protectSs.setDomainEdit(false);
}
}
Can someone help?
Best Answer
The line
does not have the desired effect because the method
protect
actually creates a new protection, which you then remove withremove
. What you need is to get the existing protection with range A:A.Unfortunately, there is no
getProtection()
method of a Range object. One has to callgetProtections
on the sheet (or spreadsheet), and then search through the returned array of protections until you find the one you need. You can search either by range (callinggetRange
on each Protection object) or, which is more robust, by description.