Google Sheets: Exclude the current date row from protection

前提是你 提交于 2019-12-02 17:47:28

问题


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 row into an array that can contain various entries.



来源:https://stackoverflow.com/questions/58060110/google-sheets-exclude-the-current-date-row-from-protection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!