简体   繁体   中英

Google Apps-Script - How to lock a range of data using today's date and reference date

I would like to lock a row of data after they have been filled in using the date as a reference. Every time a data is captured the date would be automatically logged in column A of the google sheet. Using that logged date as a reference and comparing it with today's date. If the difference is 4 days the row would be locked and would not be able to be edited.

Answer:

You can lock ranges of a Google Sheet from being edited with the Range.protect() method.

Example Code:

You need to create a Protection range by using the Range.protect() method which defines the range you need. As per the Apps Script example:

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); 
  }
}

You can then create an Installable Trigger which runs each day, comparing the current date with the date in the cell you need:

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

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

Note: The comparison to 345600000 is a Unix time - 345600000ms equals 4 days, so if more than 4 days have passed since the date in the cell you are checking (in my example function, A1), then the code will run.

References:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM