【问题标题】:Change Background Color When Cell Contains That Colors Name当单元格包含该颜色名称时更改背景颜色
【发布时间】:2016-08-10 14:14:17
【问题描述】:

我有一个 Google 表格文档,用作工作时间表。我目前正在使用以下脚本根据“K”列中的数字对整个行背景进行排序和更改;但是,我现在想知道如何根据输入的内容更改“I”列的背景颜色。因此,例如,如果我在该列中输入“红色”,我希望只有单个单元格的背景变为红色。

我知道使用条件格式很容易做到这一点,但是我不断地在此工作表中添加新行并将其他行移动到另一页,因此条件格式很快就会失去正确应用它的范围(如果有意义的话)

谢谢!

function onEdit(e) {
  if(e.range.columnStart === 11) {  
    // color the row according to the color codes and logic shown below 
    var refs = [14, "#93c47d", 15, " #00ffff", 16, "#f4c432", 17, "#ff00ff", 20, "#ffff00", ,"#ffffff"], index;

    if(e.value >= 1 && e.value < 14) {
      index = 0;
    } else if(refs.indexOf(Number(e.value)) !== -1) {
      index = refs.indexOf(Number(e.value));
    } else {
      index = refs.length - 2;
    } 

    var r = e.range.rowStart, A1 = r + ":" + r;
    e.source.getRange(A1).setBackground(refs[index + 1]);

    // sort the range after coloring
    e.source.getRange("A:K").sort({column: 11});  
  }
}

【问题讨论】:

    标签: javascript google-sheets


    【解决方案1】:

    输入你的if 后我要做的第一件事就是让你的refs 成为一个对象而不是一个数组:

    var refs = {
     green: "#93c47d",
     aqua: "#00ffff",
     orange: "#f4c432",
     magenta:"#ff00ff",
     yellow: "#ffff00"
    };
    

    然后您可以根据对象中键的存在来获得所需的颜色,即当您键入“橙色”时,您会拉取与其关联的颜色值,#f4c432。这样您就不必记住颜色代码。

    var color;
    if(refs[e.value]){  // If this key exists, use its value
      color = refs[e.value];
    } else {
      color = "#ffffff";  // Default value
    }
    

    最后可以设置行的颜色了:

    var row = e.range.getRow();
    e.source.getRange(row,1,1,e.source.getMaxColumns()).setBackground(color);
    

    并完成您的排序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-24
      • 2013-04-12
      • 2021-10-31
      • 1970-01-01
      • 2015-10-21
      • 2019-05-22
      • 2013-06-28
      相关资源
      最近更新 更多