问题
Recently ability to manipulate protection for a range programatically has been added. But is there a way to add multiple ranges all together when they have same protection to apply protection instead of processing each range one at a time? The following code is from Google sample script. Currently I am running the following code as many as ranges I have. Is there a better way to do it all at once?
var ss = SpreadsheetApp.getActive();
var range = ss.getRange('A1:B10');
var protection = range.protect().setDescription('Sample protected range');
// Protect the active sheet except B2:C5, then remove all other users from the list of editors.
var sheet = SpreadsheetApp.getActiveSheet();
var protection = sheet.protect().setDescription('Sample protected sheet');
var unprotected = sheet.getRange('B2:C5');
protection.setUnprotectedRanges([unprotected]);
// Ensure the current user is an editor before removing others. Otherwise, if the user's edit
// permission comes from a group, the script will throw an exception upon removing the group.
var me = Session.getEffectiveUser();
protection.addEditor(me);
protection.removeEditors(protection.getEditors());
if (protection.canDomainEdit()) {
protection.setDomainEdit(false);
}
Thanks.
回答1:
The brackets[] in:
protection.setUnprotectedRanges([unprotected]);
suggests that an array is expected. Have you tried:
protection.setUnprotectedRanges([sheet.getRange("B2:B5"),
sheet.getRange("F2:F5"),
sheet.getRange("H2:H5")]);
回答2:
It is not possible to manipulate non-contiguous cells in Google Spreadsheet (yet?), but there are optimiziations that can be done, setting the ranges asynchronously with HTML calls, threaded, protecting all then unprotecting some, all depends on your case, can you give an example on how your using it, how much cells you're protecting?
Updating: To do asynchronous HTML calls you would first create a sideBar or a modelessDialog, and make a button that execute many google.script.run functions. Since the code in the HTML page is asynchronous (it continous to run even though the function in google servers isn't done), you can make dozens of calls, E.G.:
In javascript HTML:
function protectOdds(){
for(var i = 0; i < 10; i++)
google.script.run.protectCells( i );
}
This would run alot faster than calling trough the .gs code to protect one at a time.
回答3:
It might be a little late, but here is what I did.
Var ranges = [ss.getRange('A1:B10'), ss.getRange('C1:E10')];
for (var i = 0; i < ranges.length; i++){
var protection = ranges[i].protect().setDescription('Sample protected range');
}
来源:https://stackoverflow.com/questions/28586183/processing-apply-protection-on-multiple-ranges-all-together