问题
I have a table in Google Sheets in the format:
A B C
Day Date inventory demand
Day2 Date2 inventory demand
etc.
Others are required to fill in inventory and demand every day. However, they should only fill out demand and inventory of the current day. They are also not allowed to change previous data or in advance fill in future days inventory and demand. Therefore, I want to protect the whole sheet from being edited by others, except the row with the current date. For example today (23.09) they should be able to edit the row where B is 23.09.2019 and nothing else.
Could somebody please help me? Thank you.
回答1:
The workflow can be as following
- Loop through all sheet rows comparing the date in column B against today
- Return the row index with today's date
- Remove all existing sheet protections
- Create a protection that protects the whole sheet with exception of the row containing today's date with
setUnprotectedRanges
Sample:
function myFunction() {
var sheet=SpreadsheetApp.getActive().getActiveSheet();
var range=sheet.getDataRange();
var values=range.getValues();
var today=new Date();
today.setHours(0);
today.setMinutes(0);
today.setSeconds(0);
today.setMilliseconds(0);
var todayMs=today.getTime();
for(var i=0;i<values.length;i++){
var date=values[i][1];
var dateMs=date.getTime();
if(dateMs==todayMs){
var row=i+1;
break;
}
}
var protections=sheet.getProtections(SpreadsheetApp.ProtectionType.SHEET);
for (var i = 0; i < protections.length; i++) {
var protection = protections[i];
if (protection.canEdit()) {
protection.remove();
}
}
var myProtection = sheet.protect().setDescription('Sample protected range');
var rangeToday=sheet.getRange(row, 1, 1, sheet.getLastColumn());
myProtection.setUnprotectedRanges([rangeToday]);
myProtection.removeEditors(myProtection.getEditors());
}
Note: This code exits the loop after finding the first row containing today's date. Should you have several rows with the same date, you need to modify the code by converting
rowinto an array that can contain various entries.
来源:https://stackoverflow.com/questions/58060110/google-sheets-exclude-the-current-date-row-from-protection