Script summery:
- The script should loop over sheets protection and ranges protection and find a target sheet and target range.
- Then, check if the current user has editor's permissions.
- If not - the script checks if the number of users with editor's permission for the target sheet and target range is smaller than the number in the permitted user emails list.
- If so - the script removes all permissions from target sheet and target range and re-set them to the permitted user emails list.
- If not - the script checks if the number of users with editor's permission for the target sheet and target range is smaller than the number in the permitted user emails list.
My problem: I get this error:
TypeError: Cannot read property 'getRange' of undefined at [the
getRangeproperties of both while loops conditions]
The script:
function someFunction() {
var ss = SpreadsheetApp.getActive();
var sheetName = 'some sheet name';
var rangeName = 'some range name';
var targetSheet = ss.getSheetByName(sheetName);
var targetRange = ss.getRangeByName(rangeName);
// set permissions
var permittedUserEmails = ['user1@gmail.com','user2@gmail.com','user3@gmail.com','user4@gmail.com','user5@gmail.com'];
var sheetProtections = ss.getProtections(SpreadsheetApp.ProtectionType.SHEET);
var rangeProtections = ss.getProtections(SpreadsheetApp.ProtectionType.RANGE);
var i = 0;
while (sheetProtections[i].getRange().getSheet() != targetSheet {
i++;
}
if (sheetProtections[i].canEdit() == false) {
if (rangeProtections[i].getEditors().length < permittedUserEmails.length) {
sheetProtections[i].remove();
sheetProtections[i].addEditors(permittedUserEmails);
}
}
var j = 0;
while (rangeProtections[j].getRange() != targetRange {
j++;
}
if (rangeProtections[j].canEdit() == false) {
if (rangeProtections[j].getEditors().length < permittedUserEmails.length) {
rangeProtections[j].remove();
rangeProtections[j].addEditors(permittedUserEmails);
}
}
}
Note:
- If I use
Browser.msgBox(sheetProtections[i].getRange())andBrowser.msgBox(rangeProtections[j].getRange())just before the correspondingwhileloops I do not get an error at all. - user1@gmail.com is the ss owner.
Can someone please explain what is going on and how to fix this?
Update:
The error was caused due to i and j exceeded the sheetProtections and rangeProtections length, correspondingly without meeting the loops conditions.
A different approach to indicate the target sheet and range solved the problem.