You can use this sample code: (this should work for columns Monday-Friday)
function onEdit(e) {
var ss = e.source; // get spreadsheet
var sheet = ss.getActiveSheet();
var cell = e.range; // get edited range
if(sheet.getName() != "Rep1"){
return;
}
var maxAppointments = sheet.getRange('G3').getValue();
var row = cell.getRow();
var col = cell.getColumn();
//Check if edited cell is within B5:F27
if(row>=5 && row<=27 && col>=2 && col<=6){
//Get current date user count
var count = sheet.getRange(3,col).getValue();
if(count>=maxAppointments){
//Select Row 5 to Row 27
var range = sheet.getRange(5,col,23);
// Protect range
var protection = range.protect();
var name = 'Column'+col;
protection.setDescription(name);
Logger.log(protection.getEditors());
protection.removeEditors(protection.getEditors());
var me = Session.getEffectiveUser();
protection.addEditor(me);
Logger.log(protection.getEditors());
if (protection.canDomainEdit()) {
protection.setDomainEdit(false);
}
}else{
var protections = sheet.getProtections(SpreadsheetApp.ProtectionType.RANGE);
Logger.log("Length"+protections.length);
for (var i = 0; i < protections.length; i++) {
var protection = protections[i];
Logger.log(protection.getDescription());
if (protection.getDescription() == 'Column'+col) {
Logger.log("remove");
protection.remove();
}
}
}
}
}
I added some guarding in your current onEdit(), such as modified cell should be in sheet "Rep1", modified cells should be within B5:F27 (done by checking row and column index)
What it does?
Check if modified cell is in Sheet Rep1 and within B5:F27 by getting its sheet name using Sheet.getName(), Row and Column Index using Range.getRow()/Range.getColumn()
If current user count on a specific day is >= the max allowed user count, protect the specific column from row5 to row 27 using Sheet.getRange(row, column, numRows) and Range.protect(). Set the description to "Column"+column index
If current user count a specific day is < the max allowed user count, remove the protection if there is any. Protection to be removed will be based on the protection description set in step 2
Sample Output:
-> This is the view from a non-editor user after protection. Notice that column B and D are not editable (Data validation drop-down list was hidded)
Note:
In the sample code, I just set my primary user as the editor after removing other editors. You can just apply your configuration in your original code where there are multiple editors.
I also did not modify your conditional formatting which sets the cell background to black, maybe you could revisit that since it always change the cell background of columns B-D even though not all columns were locked. See the sample output where columns B and D are locked but not column C
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…