0

Is there a way to get the current editors of a cell without having to first set permissions? The code I have below resets the permissions to the sheet default and then grabs that as the current editors as opposed to using the editors that were there before overwriting that cell with protect().

function onEdit() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var name = sheet.getRange("A4:A52").getValues();
  var setPermissions = [];  

  //Employee preferred initials in order to match last name array
  var initialsToMatchLastName = ['CC','RR'];
  //Employee last names
  var lastNames = ['Charles','Rickey'];
  var emails = ['charles@email.com','rickey@email.com'];

  name.forEach((value,v) => {
  for (var i = 0; i < lastNames.length; i++) {
    if (value[0] == lastNames[i]) {
      var protection = sheet.getRange("R" + (v + 4)).protect().setDescription('Locked_' + lastNames[i] + '_' + v);
      var users = protection.getEditors();
      //Logger.log(users);
      //Logger.log(emails[i]);
      if (users.includes(emails[i])) {
        //Do nothing.
      } else {
          protection.removeEditors(users);
          protection.addEditor(emails[i]);
      }
    }
  }
  })
}
hunter21188
  • 405
  • 2
  • 7
  • 29
  • The Sheets Class and the Spreadsheet Class both have getProtections() methods and the Protection Class has a getEditors() method which leads to the User Class which has a getEmail method – Cooper Sep 23 '22 at 23:08
  • Have you checked using `Session.getActiveUser().getEmail()` as per [reference](https://developers.google.com/apps-script/reference/base/session#getActiveUser()) – Century Tuna Sep 24 '22 at 04:33
  • 1
    Keep in mind there may be multiple existing protections that include the cell in question. [This answer](https://stackoverflow.com/questions/70328246/check-if-a-google-sheets-cell-has-protection-with-google-apps-script) may be a good starting point: it shows how to iterate over all protections on a sheet and find those that overlap with a specific cell. From there, you just need to call `.getEditors()` on each of those protections and apply your logic accordingly. – Aaron Dunigan AtLee Sep 24 '22 at 04:43

0 Answers0