根据另一个单元格值和文本颜色设置单元格背景颜色的脚本

时间:2021-05-06 20:24:37

标签: google-apps-script google-sheets formatting textstyle

我希望创建一个脚本,我可以在其中指定单元格值和文本颜色,然后触发它,它将使用绿色背景颜色为所有匹配的单元格(值和文本颜色)着色。

例如,我有一个值为“1”的单元格,文本颜色为#4285f4,我想获取该单元格的值和文本颜色,然后将其匹配到给定的范围 (A2:P60)并将与 '1' 的值和文本颜色 #4285f4 匹配的任何单元格的背景着色为绿色。

我看到有一个 textstyle 类,但我不确定如何将所有这些组合在一起。

感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

您可以使用此示例脚本作为参考:

function checkCells() {
  var ss = SpreadsheetApp.getActive().getActiveSheet();
  var refValue = ss.getRange("A1").getValue(); //Used A1 as the cell with reference value and text color value
  var refTextColor = ss.getRange("A1").getTextStyle().getForegroundColor();
  var range = "A2:D15"; //Change range if you have a different one
  var columns = ss.getRange(range).getNumColumns();
  var lastrow = ss.getRange(range).getNumRows();

  for(var col=1; col<=columns; col++ ){
    for(var row=2; row<=lastrow; row++){ //Started the loop on row2 because row 1 has the cell reference values
      if(ss.getRange(row,col).getValue() == refValue && ss.getRange(row,col).getTextStyle().getForegroundColor() == refTextColor){
        Logger.log("Value of \""+ss.getRange(row,col).getValue()+"\" from Column #"+col+" & Row #"+row+" matched reference value of \""+ refValue+"\"");
        ss.getRange(row,col).setBackground("Green");
      }
    }
  }
}

结果

样本表:

enter image description here

运行脚本后:

enter image description here

相关问题