Google 特定日期的表格应用脚本锁定单元格

Google Sheets App Script lock cells for specific days

我试图在前 10 天的每个月解锁特定范围的单元格,然后锁定该范围直到下个月。这是我一直在做的事情。但这并不像我预期的那样有效。感谢任何帮助。

function tenDaysAllowance() {
  var ss = SpreadsheetApp.getActive();
  var source = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Online Allowance");
  var todaysdate = Utilities.formatDate(new Date(), 'GMT+5', 'dd/MM/yyyy');
  var firstDate = new Date();
  var fd = firstDate;
    fd.setMonth(fd.getMonth());
    fd.setDate(1);
  var td = new Date();
    td.setMonth(td.getMonth());
    td.setDate(10);
  var firstDay = Utilities.formatDate(fd, 'GMT+5', 'dd/MM/yyyy');
  var afterTen = Utilities.formatDate(td, 'GMT+5', 'dd/MM/yyyy');
  Logger.log(firstDay);
  Logger.log(afterTen);

  if (todaysdate >= firstDay && todaysdate <= afterTen) {
    Logger.log("todays date is in range");
    var range = ss.getRange('B27:AF40');
    var protection = range.protect().setDescription('Sample protected range');
    var me = Session.getEffectiveUser();
    protection.addEditor(me);
    protection.removeEditors(protection.getEditors());
    if (protection.canDomainEdit()) {
      protection.setDomainEdit(false);
    }
  } else {
    Logger.log("todays date is not in range");
    var range = ss.getRange('B27:AF40');
    var allProtections = ss.getProtections(SpreadsheetApp.ProtectionType.RANGE);
    var matchingProtections = allProtections.filter(function(existingProtection) {
    return existingProtection.getRange().getA1Notation() == 'B27:AF40';
    });
    var protection = matchingProtections[0];
    protection.remove();
    };
};

在您的 google sheet 中使用 today() 确定今天的日期,并使用 day() 确定今天日期的值。

function myProtection() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Date Check");
var date=ss.getRange("B1");

//if it more the 10th of the month lock sheet, else allow others to edit
if(date > 10)
{
// Protect range A1:B10, then remove all other users from the list of editors.
var range = ss.getRange('B27:AF40');
var protection = range.protect().setDescription('Sample protected range');
var me = Session.getEffectiveUser();
protection.addEditor(me);
protection.removeEditors(protection.getEditors());
if (protection.canDomainEdit()) {
protection.setDomainEdit(false);
}
}


else{
    var allProtections = ss.getProtections(SpreadsheetApp.ProtectionType.RANGE);
    var matchingProtections = allProtections.filter(function(existingProtection) {
    return existingProtection.getRange().getA1Notation() == 'B27:AF40';
    });
    var protection = matchingProtections[0];
    protection.remove();
};
}