Search code examples
google-apps-scriptgoogle-sheets-macros

Clear note from cells based on conditional formatting color


I have a Google Sheet script that clears all notes in a sheet that has a trigger to run daily. I really want it to just “clear notes” in cells that are conditionally formatted green that day. As background info, the notes are automatically added to various cells by an add-on but when the cell turns green again, I want the note attached to that cell to be cleared. Is this possible? I've provided the code that I have so far but get confused with the array getRange part. Thank you!

function cleargreens() {
  var sheet1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Overview");

  var data1 = sheet1.getDataRange().getValues();  //2D array of sheet1 cell values
  var bg;

  for(var i=1; i<data1.length; i++)
  {
    bg = sheet1.getRange(i+1, 2).getBackground();
    if(bg == "#b7e1cd") //this is the conditional green color code
    {
      sheet1.getRange(i+1, 3).clearNote();
    } 

My spreadsheet, although the colors I will be searching for will only be in columns E to H


Solution

  • If all of your cells can potentially have notes which need to be removed when the background color is green - then you need to implement a nested loop, which iterates through both rows AND columns:

    function cleargreens() {
      var sheet1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Overview");
    
      var data1 = sheet1.getDataRange().getValues();  //2D array of sheet1 cell values
      var bg;
    //iterates through rows
      for(var i=1; i<data1.length; i++)
      {
    //iterates through columns    
        for(var j=1; j<data1[0].length; j++)
        {
          var cell=sheet1.getRange(i+1, j);
          bg = cell.getBackground();
          if(bg == "#b7e1cd") //this is the conditional green color code
          {
            cell.clearNote();
          }
        }
      }
    }
    

    As for your confusion, be aware that a range is a 2-D array with a row and column index.