Search code examples
google-sheetsgoogle-apps-scriptspreadsheet-protection

Allow user with edit privileges to run scripts on a spreadsheet owned by me


I have eight scripts with assigned buttons that work for me when accessing a spreadsheet. I would like to allow another user to run all of the scripts when clicking the associated button.

I understand that I can deploy a web app and execute under my name but when I try to deploy I get errors. Tried doGet(e) within the script but did not use it correctly.

What needs to be done to allow another user to click a button to run a script on a spreadsheet owned by me?

1st Script:

function LockFriday()  {
  var protectRange = 'C8:D60';
  var description = 'AA Lock Friday Cells';
  var spreadsheet = SpreadsheetApp.openById('xxxxxxxxxxxxxxxxxxxxxxx');
  spreadsheet.getRange(protectRange).activate();
  spreadsheet.setCurrentCell(spreadsheet.getRange('D60'));
  var p = spreadsheet.getProtections(SpreadsheetApp.ProtectionType.RANGE).find(e => e.getRange().getA1Notation() == protectRange && e.getDescription() == description);
  if (p) return;
  var protection = spreadsheet.getRange(protectRange).protect();
  var all = protection.getEditors();
  protection.setDescription(description).removeEditors(all);
}; 

Associated 2nd Script

function UnlockFriday() {
  var spreadsheet = SpreadsheetApp.openById('xxxxxxxxxxxxxxxx');
  spreadsheet.getRange('C8:D60').activate();
  var allProtections = spreadsheet.getActiveSheet().getProtections(SpreadsheetApp.ProtectionType.RANGE);
  var matchingProtection = allProtections.find(existingProtection => existingProtection.getRange().getA1Notation() == 'C8:D60');
  if (!matchingProtection) return;
  matchingProtection.remove();
}

Solution

  • Your scripts use SpreadsheetApp.openById, so the editors should also have access to the spreadsheet referred to by this method.

    Anyway, look at the execution logs; they might tell you what the problem is. For details, see https://developers.google.com/apps-script/guides/support/troubleshooting


    Notes:

    When using getRange with a spreadsheet, include the sheet name, i.e., assuming that the sheet name is Sheet1 instead of 'C8:D60' use 'Sheet1!C8:D60'.

    Scripts might work differently for spreadsheet owners than for editors. When making scripts run by editors, avoid using methods like activate and getCurrentCell with spreadsheets opened by openById. Use these methods only with SpreadsheetApp.getActive().