Search code examples
loopsif-statementconditional-statementsbackground-color

Cant make the condition formatting to work with a script in Google sheets


I am trying to color format a row in a spreadsheet where I run a loop to check if any of the values is equal to 0 and if it is equal to 0 to color it red and if not color it red. I know I can do it with conditional format but I need this to activate after I press a button included in the sheet, so I need a script added to the button.

I have managed to write this script but it seems it color only the last cell from the range. Can you please tell me what am I doing wrong since I am new to coding.

function FormatColor() {

  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Acontobetaling');
  var range = sheet.getRange('D34:AA34');
  var values = [];
  var cell = [];

  for (var i = 1; i <= 24; i=i+1)
    cell = range.getCell(1, i)
    values = cell.getValue();
    if (values = '0') {
      cell.setBackground('red');
      } else {
      cell.setBackground('green');
      }
}

Solution

  • I made it work, if someone is having the same problem you can use this Anyway if you can provide me with better or fast way to do it you are welcome to show me how :)

    function CopyData() {
    
      var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Acontobetaling');
      var rangeColor = sheet.getRange('D34:AA34');
      var values = [];
      var cell = [];
      var colors = [];
    
       for (var i = 1; i <= 24; i=i+1) {
        cell = rangeColor.getCell(1, i);
        values = cell.getValue();
        if (values == '0') {
          colors = cell.setBackground('red');
          } else {
          colors = cell.setBackground('green');
          }
       }