简体   繁体   中英

How to change the color of a cell based on the value of other cells in google sheets

I am aware of conditional formatting in google sheets, but I have a kind of specific use case.

I want the cell n in column A (and all the way down) to be green if ALL the cells in columns N , O or P have the word pass in them

But I want the cell n in column A to be red if ANY of the cells in N , O or P contain fail regardless if they also contain pass

Is there a way this can be done?

Explanation:

  • You can use Google Apps Script to achieve your goal and in particular an onEdit() function to mimic the automatic (on edit) updates of the conditional formatting.

  • The following script will get the values of all cells in N , O and P columns and if all of these values are pass then it will set the background color of column A to green. On the other hand, if at least one of them is not pass , it will set the color of column A to red. Feel free to change sheet_name to your own sheet name.


Solution:

function onEdit(e) {
  
 const sheet_name = 'Sheet1';
 const col = e.range.getColumn();
 const as = e.source.getActiveSheet();
 
 if(as.getName() === sheet_name && col>13 && col<17){
 
   const data = as.getRange('N1:P').getValues().flat();
   const range = as.getRange('A1:A');
   const allEqual = arr => arr.every( v => v === arr[0] );
   
   if(allEqual(data)){
     range.setBackground("green");
  }
   else {
     range.setBackground("red");
  }
 }
}

Instructions/Demonstration:

示范

If you want to use formulas instead of a script you can always use the following 2 rules:

1st rule:

...cell n in column A (and all the way down) to be green if ALL the cells in columns N , O or P have the word pass in them

=COUNTIF($B$1:$D,">""")+COUNTIF($B$1:$D,"")=COUNTIF(ArrayFormula(REGEXMATCH($B$1:$D,"\bpass\b")),true)

在此处输入图片说明

2nd rule:

...cell n in column A to be red if ANY of the cells in N , O or P contain fail regardless if they also contain pass

=COUNTIF(ArrayFormula(REGEXMATCH($B$1:$D,"\bfail\b")),true)>0

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM