首页 > 解决方案 > Google Apps-Script - 如何使用今天的日期和参考日期锁定一系列数据

问题描述

我想在使用日期作为参考填写后锁定一行数据。每次捕获数据时,日期都会自动记录在谷歌表的 A 列中。使用该记录的日期作为参考并将其与今天的日期进行比较。如果差值为 4 天,则该行将被锁定并且无法编辑。

标签: google-apps-script

解决方案


回答:

您可以使用 Range.protect() 方法锁定 Google 表格的范围,使其不被编辑。

示例代码:

Range.protect()您需要使用定义所需范围的方法来创建保护范围。根据 Apps 脚本示例:

function doProtections() {
  var ss = SpreadsheetApp.getActive();
  var range = ss.getRange('A1:Z1'); // Example of protecting Row 1
  var protection = range.protect().setDescription('Protected range name');

  var me = Session.getEffectiveUser();
  protection.addEditor(me);
  protection.removeEditors(protection.getEditors());
  if (protection.canDomainEdit()) {
    protection.setDomainEdit(false); 
  }
}

然后,您可以创建一个每天运行的可安装触发器,将当前日期与您需要的单元格中的日期进行比较:

function runEachDay() {
  var today = new Date()
  var dateToCheckAgainst = new Date(SpreadsheetApp.getActiveSpreadsheet().getSheets()[0].getRange('A1').getValue())

  if (today.getTime() - dateToCheckAgainst.getTime() > 345600000) {
    doProtections();
  }
}

注意:比较的345600000是 Unix 时间 - 345600000ms 等于 4 天,所以如果自您检查的单元格中的日期(在我的示例函数 A1 中)以来已经过去了 4 天以上,那么代码将运行。

参考:


推荐阅读