3

I can lock by color, but need to also to lock only the white cells (ffffff) that contain any content.

 var ss = SpreadsheetApp.getActiveSpreadsheet(); //clears green feilds
  var sheet = ss.getSheetByName("Sheet1");
  var color = sheet.getRange('C23').getBackground()
  var range = sheet.getDataRange();
  var bgColors = range.getBackgrounds();
 var data = range.getValues();
var formulas = range.getFormulas(); // Added
for (var i = 0; i < bgColors.length; i++) {
  for (var j = 0; j < bgColors[i].length; j++) {
    if (bgColors[i][j] == color) {
      data[i][j] = '';
    }
  }`enter code here`
}
formulas.forEach((r, i) => r.forEach((c, j) => { // Added
  if (c) data[i][j] = c;
}));
   range.setValues(data).setBackgrounds(bgColors);//reset values and backgrounds    
TheMaster
  • 45,448
  • 6
  • 62
  • 85

1 Answers1

0

If I understand correctly what you need is to protect cells that have the same color from cell C23 and also the ones that are white but don't have an empty value on them. If so, you can try something like this:

function myFunction() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Sheet1");
  var color = sheet.getRange('C23').getBackground()
  var range = sheet.getDataRange();
  var bgColors = range.getBackgrounds();
  var data = range.getValues();
  var formulas = range.getFormulas(); // Added

  for(var i=0; i< bgColors.length; i++)
  {
    for(var j=0; j < bgColors[i].length; j++)
    {
      if((bgColors[i][j] == color)||(bgColors[i][j] == "#ffffff" && data[i][j] != "" ))
      {
        var protection = range.getCell(i+1, j+1).protect();
        var editors = protection.getEditors();
        protection.removeEditors(editors);
        //protects the cell that matches the criteria and removes any editor
        //so that only you have access to edit it
      }
    }
  }

  formulas.forEach((r, i) => r.forEach((c, j) => { // Added
  if (c) data[i][j] = c;
  }));
  range.setValues(data).setBackgrounds(bgColors);//reset values and backgrounds
}

Let me know if that works for you, or if the criteria you are using is different so that I can change the script.

References:

Fernando Lara
  • 2,263
  • 2
  • 4
  • 14