google-apps-scriptgoogle-sheetsgoogle-sheets-macros

How to add one more row and double of selected rows to the protected data using getRange() or getActiveRange() in Google Apps Script?


I manually select A41 to F80 and it is nicely protecting A41 to F80 using the following line of code.

However, I want to (i) add one more row to the protected data (A41 to F81) though I will select A41 to F80.

Also in another case I want to add double of selected rows plus one to the protected data (A41:F121) though I will select A41 to F80.

Probably getActiveRange() won't work, then I tried to use getRange() but can't solve it. Please help me to solve it.

var protection = SpreadsheetApp.getActiveSheet().getActiveRange().protect().setDescription(description); 

Solution

  • You need to create a new range

    Sample:

    var activeRange = SpreadsheetApp.getActiveRange();
    var height = activeRange.getHeight();
    var newHeight = height + 1;
    var activeSheet = SpreadsheetApp.getActiveSheet();
    var newRange = activeSheet.getRange(activeRange.getRow(), activeRange.getColumn(), newHeight, activeRange.getWidth());
    var protection = newRange.protect().setDescription(description);