如何更改谷歌电子表格行的颜色,当行中的单元格编辑?(How to change a google s

2019-06-23 16:28发布

我已经尝试过这样的: 谷歌电子表格:脚本来改变行颜色时,细胞改变文本;

但它不能得到它的工作。 该行的颜色不会更改为#000000

这是我到目前为止有:

function onEdit(event)
{
  var ss = event.source.getActiveSheet();
  var r = event.source.getActiveRange();

  var currentValue = r.getValue();

  if(currentValue == "dags dato")
  {
    var dd = Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd");
    r.setValue(dd);
  }
  else if(currentValue == "dialog")
  {
    setRowColor("yellow");
  }
  else if(currentValue == "besvaret")
  {
    setRowColor("yellow");
  }
  else if(currentValue == "afvist")
  {
    setRowColor("red");
  }
}

function setRowColor(color)
{
  var range = SpreadsheetApp.getActiveSheet().getDataRange();
  var statusColumnOffset = getStatusColumnOffset();

  for (var i = range.getRow(); i < range.getLastRow(); i++) {
    rowRange = range.offset(i, 0, 1);
    status = rowRange.offset(0, statusColumnOffset).getValue();

    rowRange.setBackgroundColor("#000000");

}


//Returns the offset value of the column titled "Status"
//(eg, if the 7th column is labeled "Status", this function returns 6)
function getStatusColumnOffset() {

  lastColumn = SpreadsheetApp.getActiveSheet().getLastColumn();
  var range = SpreadsheetApp.getActiveSheet().getRange(1,1,1,lastColumn);

  for (var i = 0; i < range.getLastColumn(); i++) {
    if (range.offset(0, i, 1, 1).getValue() == "Status") {
      return i;
    } 
  }
}

Answer 1:

我写的方式更快和更清洁的方法为我自己和我想分享它。

function onEdit(e) {
    if (e) { 
        var ss = e.source.getActiveSheet();
        var r = e.source.getActiveRange(); 

        // If you want to be specific
        // do not work in first row
        // do not work in other sheets except "MySheet"
        if (r.getRow() != 1 && ss.getName() == "MySheet") {

            // E.g. status column is 2nd (B)
            status = ss.getRange(r.getRow(), 2).getValue();

            // Specify the range with which You want to highlight
            // with some reading of API you can easily modify the range selection properties
            // (e.g. to automatically select all columns)
            rowRange = ss.getRange(r.getRow(),1,1,19);

            // This changes font color
            if (status == 'YES') {
                rowRange.setFontColor("#999999");
            } else if (status == 'N/A') {
                rowRange.setFontColor("#999999");
            // DEFAULT
            } else if (status == '') { 
                rowRange.setFontColor("#000000");
            }   
        }
    }
}


Answer 2:

你可以尝试使用Logger类,像这样来检查你的任何错误或问题的代码:

try {
    //your code
}
catch(e) {
    Logger.log(e);
}

然后,你可以去查看 - >看到从脚本编辑器日志如果每一行代码的预期相符。 另外,执行纪录可能是有用的,看看代码处断裂的代码一个特定的行。 您可以查看每个故障的排除方法是如何工作的更多详细信息 。



文章来源: How to change a google spreadsheet row color, when a cell in the row is edited?