๐Protection
// 1. get range A1:B10,
var ss = SpreadsheetApp.getActive();
var range = ss.getRange('A1:B10');
// 2. protect range
var protection = range.protect().setDescription('Sample protected range');
// 3. ensure current user is editor before removing.
// (Otherwise, if the user's edit permission comes from a group,
// the script throws an exception upon removing the group.)
var me = Session.getEffectiveUser();
protection.addEditor(me);
// 4. then remove all other users from the list of editors.
protection.removeEditors(protection.getEditors());
if (protection.canDomainEdit()) {
protection.setDomainEdit(false);
}
// Protect the active sheet, then remove all other users (from edit)
var sheet = SpreadsheetApp.getActiveSheet();
var protection = sheet.protect().setDescription('Sample protected sheet');
// Ensure the current user is an editor before removing others.
// Otherwise, if the user's edit permission comes from a group,
// the script throws an exception upon removing the group.
var me = Session.getEffectiveUser();
protection.addEditor(me);
protection.removeEditors(protection.getEditors());
if (protection.canDomainEdit()) {
protection.setDomainEdit(false);
}
// --------------------------------------
// protect sheet, unprotect range
// --------------------------------------
var protection = sheet.protect();
protection.setUnprotectedRanges([ranges]);
// Remove all range protections in the spreadsheet
// that the user has permission to edit.
var ss = SpreadsheetApp.getActive();
var protections = ss.getProtections(SpreadsheetApp.ProtectionType.RANGE);
for (var i = 0; i < protections.length; i++) {
var protection = protections[i];
if (protection.canEdit()) { protection.remove() }
}
GAS โฉ Protection - protect / unprotect range / sheet.
Last updated