Home > Back-end >  Google Sheet Remove Editors After First Edit
Google Sheet Remove Editors After First Edit

Time:06-07

I am trying to lock a cell in Google Sheet after the first entry in the cell and using below code and getting correct result. However,in this code a cell is locked after first entry but the owner and the editor can make further edits to the locked cell, however, I want to lock the cell for even the person who entered the data i.e. only the owner can make edit to the cell after it is lockedenter code here.

function onEdit(e){
  let protection = e.range.protect();
  protection.removeEditors(protection.getEditors());
  if (protection.canDomainEdit()) {
  protection.setDomainEdit(false);
  }
  } 

Any help on above will be appreciated.Below is the link of the sheet:

https://docs.google.com/spreadsheets/d/14qFZOKYUiQL4gKuLfdHPQwOgQ5LoY5P7KZyHN8ev-qY/edit?usp=sharing

CodePudding user response:

If your script is run by the simple trigger of OnEdit, I think that the reason for your issue might be due to this. In this case, please use the installable OnEdit trigger.

When you install the installable OnEdit trigger, please rename the function name. Because when onEdit function is installed as the installable trigger, when a cell is edited, 2 times of onEdit is run with the asynchronous process. Please be careful about this.

So, how about the following modification?

Modified script:

function installedOnEdit(e) {
  let protection = e.range.protect();
  protection.removeEditors(protection.getEditors());
  if (protection.canDomainEdit()) {
    protection.setDomainEdit(false);
  }
}

function installTrigger() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  ScriptApp.newTrigger("installedOnEdit").forSpreadsheet(ss).onEdit().create();
}
  • In this script, when installTrigger is run, the installable OnEdit trigger is installed to the function installedOnEdit. By this, when a user who is not the owner of the Spreadsheet edits a cell, the cell is protected.

Reference:

Added:

About your following new question,

I want to lock the sheet for the editor also i.e. only owner can edit the sheet.

In this case, please modify the above script as follows.

Modified script:

function installedOnEdit(e) {
  let protection = e.range.getSheet().protect();
  protection.removeEditors(protection.getEditors());
  if (protection.canDomainEdit()) {
    protection.setDomainEdit(false);
  }
}
  • By the way, in this script, it supposes that you are the owner of the Spreadsheet, and you install the OnEdit trigger. So, if you want to install OnEdit trigger using installTrigger, please run the script by the owner. Please be careful about this.
  • Related