Google App Script - Conditional Formatting Based on Another Cell

后端 未结 2 1235
没有蜡笔的小新
没有蜡笔的小新 2021-01-26 09:29

I am trying to figure out how to use conditional formatting via script on a google spreadsheet similar to what you can do with the conditional formatting feature.

I have

2条回答
  •  有刺的猬
    2021-01-26 09:57

    Try copy and pasting this into a blank script file. This depends on column A being Country, and column B being State, but you can make as many sheets as you want, and this will work automatically.

    Let me know if you want an explanation of a specific part, as I'm not sure what your scripting background is. I've included some comments in the code.

    function onEdit(e) {
    
      var ss = e.source;
      var sheet = ss.getActiveSheet();
      var range = sheet.getRange("A:B");
      var values = range.getValues();
    
      //for each row that data is present
      for(var i = 0; i < values.length; i++) {
        var cell = sheet.getRange(i + 1, 2);
    
        //check if the first value of that row is exactly "United States"
        if(values[i][0] === "United States") {
    
          //if it is, check for a blank cell.  If so, make it red.
          if(values[i][1] === "") {
            cell.setBackground('red');
          } else {
            cell.setBackground('white');
          }
    
        } else {
    
          //In any other case, make it white.
          cell.setBackground('white');
        }
      }  
    }    
    

提交回复
热议问题