Color cell RED if cell above value is lower

前端 未结 2 1781
粉色の甜心
粉色の甜心 2021-01-24 15:28

I need a formula/script for a Google spreadsheet that will do this:

If the current cell value is higher than the value in the cell above the make the current cell backgr

2条回答
  •  广开言路
    2021-01-24 15:57

    You can use an onEdit() trigger to react to changes by reading the value from the cell above the one-just-changed, making the comparison, and coloring appropriately. You must do this in a script, you cannot control color from custom functions.

    You said "If the current cell value is higher than the value in the cell above...", but your example then had =IF((C34>B34)..., which is "beside", not "above". This code uses .offset(-1,0) for "above", and ensures it won't mess with the row above row 1 - if you meant "beside", you'll want to change that.

    function onEdit(event)
    {
      if (isNaN(event.value)) return;        // If change was not a number, exit
      var changedCell = event.range;
      if (changedCell.getRow() == 1) return; // Nothing to do in Row 1
      var cellAbove = changedCell.offset(-1, 0);
      var background = 'white';              // Assume white background
      // Is the changed value greater than the value in the cell above?
      if ( parseFloat(event.value) > parseFloat(cellAbove.getValue()) ) {
        background = 'red';                  // Yes, so red background
      }
      changedCell.setBackground(background);
    }
    

    WRT performance, the trigger function will slow things a bit, but I suspect you'll see a greater lag due to the large number of multiple viewers, as google-docs does it thing to keep all those disparate views in sync. (I've seen sheets with < 100 cells and no formulas struggle to keep up with < 10 viewers.)

提交回复
热议问题