How to lock a Google Sheet during a specific time period everyday

google sheets

My google spreadsheet should only be editable between 12 AM to 8 AM everyday.

How do I accomplish this?

Best Answer

With a script, one can add sheet protection using protect method, and remove it using remove method. Using time-driven triggers, set the following functions to run daily, protectAll should run at 8am and unprotectAll at 12am.

Both functions loop over all sheets in the active spreadsheet, protecting or unprotecting them.

function protectAll() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheets = ss.getSheets();
  for (var i = 0; i < sheets.length; i++) {
    sheets[i].protect().setDescription("Temporary protection");
  }
}

function unprotectAll() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheets = ss.getSheets();
  for (var i = 0; i < sheets.length; i++) {
    var protection = sheet.getProtections(SpreadsheetApp.ProtectionType.SHEET)[0];
    if (protection) {
      protection.remove();
    }
  }
}