我需要删除对有权访问某些单元但在脚本运行时需要所有行和列的用户的保护。之后,除了可编辑单元格之外,我还需要再次保护工作表。
// Unprotect cells F:AP in addition to any other unprotected ranges in the protected sheet.
var sheet = SpreadsheetApp.getActiveSheet();
var protection = sheet.protect();
var unprotected = protection.getUnprotectedRanges();
unprotected.push(sheet.getRange('F:AP'));
protection.setUnprotectedRanges(unprotected);
// Hides columns
var sheet = ss.getSheets()[1];
var range = sheet.getRange("F:AP");
sheet.hideColumn(range);
上面的代码对我有用,但是对于其他人,由于他们没有编辑权限,它会引发错误。
为了保护工作表远离可编辑的行,可以使用此代码,
function protectsheet() {
// Protect the active sheet, then remove all other users from the list of editors.
var sheet = SpreadsheetApp.getActiveSheet();
var protection = sheet.protect().setDescription('Protected sheet');
var ranges = protection.getUnprotectedRanges();
var range1 = sheet.getRange("A2:B6"); //Replace the range with the editable cells
var range2 = sheet.getRange("D2:D6"); //Replace the range with the editable cells
//Skip this if you have one range
ranges.push(range1);
ranges.push(range2); //Skip this if you have one range
protection.setUnprotectedRanges(ranges); //This combines both the ranges into an array
// 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);
}
protection.addEditors(["EmailID"])
}
希望这会有所帮助!