0

I am trying to edit a Google Sheet via Apps script, but whenever the code tries to edit a protected range the execution stops with an error

You are trying to edit a protected cell or object. Please contact the spreadsheet owner to remove protection if you need to edit.

Despite using try and catch the script fails to catch the error. Please suggest ways to catch this error.

Below is the code that I have used: In case you wish to test the scenario, The sheet used below has general access and the range MasterData!A2:G3 is protected.

function myFunction() {

try{
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1TCSNpk4zUhoHo_fUDYbr-jtXCI8U1lWJlhqwNP9C5V4/edit#gid=0");
  var backendsheet=ss.getSheetByName("MasterData");
  backendsheet.getRange(2,2).setValue("ABC");
}
catch(err)
{
  Logger.log("Error Name:" +err.name);
  Logger.log("Error Message:" +err.message);
}
}
James Z
  • 12,209
  • 10
  • 24
  • 44
Sukesh
  • 13
  • 1
  • 8

1 Answers1

0

In your situation, I thought that in order to confirm whether you can edit the range, canEdit method might be able to be used. When this is reflected in your script, it becomes as follows.

Modified script:

function myFunction() {
  var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1TCSNpk4zUhoHo_fUDYbr-jtXCI8U1lWJlhqwNP9C5V4/edit#gid=0");
  var backendsheet=ss.getSheetByName("MasterData");
  
  // I modified below script.
  var range = backendsheet.getRange(2, 2);
  if (range.canEdit()) {
    console.log("Your account can edit this range.");
  } else {
    console.log("Your account cannot edit this range.");
  }
}
  • For example, when the range of backendsheet.getRange(2, 2) is protected range and you cannot edit, range.canEdit() return false.

Reference:

Tanaike
  • 181,128
  • 11
  • 97
  • 165