How to check if a cell in Google Sheets has protection with Google Apps Script? Specifically, range protection, not sheet protection.
To check if a cell with coordinates row
and col
(starting from 1) has protection use:
function has_protection(row,col) { // row and column starting from 1
var sheet = SpreadsheetApp.getActiveSheet();
var cell_has_protection = false;
var protections = sheet.getProtections(SpreadsheetApp.ProtectionType.RANGE); // get all protected ranges
if ( protections != '' ) {
for (var p = 0; p < protections.length; p++) {
var pro_range = protections[p].getRange(); // each protected range
if (row >= pro_range.getRow()
&& row <= (pro_range.getRow() + pro_range.getHeight() - 1)
&& col >= pro_range.getColumn()
&& col <= (pro_range.getColumn() + pro_range.getWidth() - 1)) {
cell_has_protection = true;
}
}
}
return cell_has_protection;
}
You can also highlight all the protected cells on the sheet with the following code (it will clear all other highlights on the sheet and fill only the protected):
function color_protected(){
var sheet = SpreadsheetApp.getActiveSheet();
var protections = sheet.getProtections(SpreadsheetApp.ProtectionType.RANGE);
if ( protections != '' ) {
sheet.getRange('1:' + sheet.getMaxRows()).setBackground(null); // clear all background on the sheet
for (var p = 0; p < protections.length; p++) {
var pro_range = protections[p].getRange();
//Logger.log(pro_range.getA1Notation());
pro_range.setBackground('#fbbc04'); // color protected range
}
}
}