if-statementgoogle-apps-scriptgoogle-sheetsformattinggetvalue

Trying to conditional format Google sheet that uses a Google form for data entry


I have moved over to using google forms for data entry to try and improve data integrity. However, the conditional formatting is thrown off after ever new entry is added onto the bottom of the sheet. It means constantly having to change the formatting range manually, which isnt a lot of work but a bit frustrating when you want to leave the sheet running by itself.

I am new to apps script (and coding in general!) but have been trying to piece together something that might work. I want the cells in column A (A4:A) to change colour depending on the value of the cell. So far I have the below - which works for Row 4 but none of the other rows. Im struggling to get the code to recognise that there is more data below the first row.

The error I'm getting says:

"The number of rows in the data does not match the number of rows in the range. The data has 1 but the range has 196."

function conditionalformatting(e) {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Warehouse Queries');
  var range = sheet.getRange(4,1,sheet.getLastRow(),1);
  var cellvalues= range.getValues(); 
  var colors = [];

     if (cellvalues = 'Warehouse Admin to Action') {
      colors.push(["#6db05f"]);} 
      else if (cellvalues = 'Warehouse Coordinator to Action') {
      colors.push(["#f0c784"]);} 
      else if (cellvalues = 'POD required - Supply Chain to source') {
      colors.push(["#84bef0"]);} 
      else {colors.push([""]);}

      range.setBackgrounds(colors);
      }

Thanks!


Solution

  • Modification points:

    When these points are reflected in your script, how about the following modification?

    Modified script:

    function conditionalformatting(e) {
      var obj = {
        'Warehouse Admin to Action': "#6db05f",
        'Warehouse Coordinator to Action': "#f0c784",
        'POD required - Supply Chain to source': "#84bef0",
      };
      var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Warehouse Queries');
      var range = sheet.getRange("A4:A" + sheet.getLastRow());
      var cellvalues = range.getValues();
      var colors = cellvalues.map(([a]) => [obj[a] || null]);
      range.setBackgrounds(colors);
    }
    

    Reference: