I'm trying to protect a specific range until the last row, but after trying to consider the possibility of having empty rows in the way, I couldn't get the expected result.
In my example: I'm trying to protect a range of A:D and since the last row containing data is C24, the script should protect A2:D24. Column F (and anything else) is ignored in my script.
Screenshot:
I'm getting the following error: Exception: The number of rows in the range must be at least 1
for line 30 corresponding to var rangeToProtect = ss.getRange(2,1,(lr-1), 4);
My script:
function getLastRow(sheet,rangeString) {
var rng = sheet.getRange(rangeString).getValues();
var lrIndex;
for(var i = rng.length-1;i>=0;i--){
lrIndex = i;
if(!rng[i].every(function(c){ return c == ""; })){
break;
}
}
var lr = lrIndex + 1
Logger.log(lr);
}
function protectData(){
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
var curDate = Utilities.formatDate(new Date(), "GMT", "EEE d MMM yyyy HH:mm:ss")
var lr = getLastRow(ss,"A2:D");
var rangeToProtect = ss.getRange(2,1,(lr-1), 4);
var protection = rangeToProtect.protect().setDescription(curDate);
protection.removeEditors(protection.getEditors());
}
// Function edited with suggestions:
function protectImportedData(){
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
var curDate = Utilities.formatDate(new Date(), "GMT+3", "EEE d MMM yyyy HH:mm:ss")
var Direction = SpreadsheetApp.Direction;
var aLast =ss.getRange("A1:D"+(ss.getLastRow()+1)).getNextDataCell(Direction.UP).getRow();
var rangeToProtect = ss.getRange(2,1,(aLast-1), 4);
var protection = rangeToProtect.protect().setDescription(curDate);
protection.removeEditors(protection.getEditors());
}