How to target and iterate through just one specific column (by column name) in Google sheets / apps script?
所以我有一个 OnEdit 函数,它检测数据何时被复制并粘贴到电子表格中,然后在找到颜色值的地方,单元格背景颜色变为该颜色。
但是,目前它正在遍历电子表格中的每个单元格,这在复制和粘贴数据时非常慢。我只希望它在我的电子表格的 "CategoryColor" 列中迭代并检测复制和粘贴的更改。
这是我目前所拥有的,任何帮助将不胜感激!谢谢!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | function onEdit(e) { var firstRow = e.range.getLastRow() - e.range.getHeight() + 1; var firstColumn = e.range.getLastColumn() - e.range.getWidth() + 1; var values = e.range.getValues(); for (var i = 0; i < e.range.getHeight(); i++) { for (var j = 0; j < e.range.getWidth(); j++) { try { // changes background colour of cell e.source.getActiveSheet().getRange(firstRow + i, firstColumn + j).setBackground(values[i][j]); } catch (e) { Logger.log(e); } } } // sets data validation setDataValidation(createColorList()); getColumnData(activeSpreadsheet); getFullColumn(columnIndex, startIndex); } |
您只需要执行一个
使用方法 indexOf() 查找正确列的示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | function onEdit(e) { var sheet=e.source.getActiveSheet(); var headers=sheet.getRange(1,1,1, sheet.getLastColumn()).getValues; //assuming the headers are in row 1, otherwise change it accordingly var column=headers[0].indexOf("CategoryColor")+1; //finds the column with the header"CategoryColor" if(e.range.getColumn()==column){ // YOUR SCRIPT var firstRow = e.range.getLastRow() - e.range.getHeight() + 1; var firstColumn = e.range.getLastColumn() - e.range.getWidth() + 1; var values = e.range.getValues(); for (var i = 0; i < e.range.getHeight(); i++) { for (var j = 0; j < e.range.getWidth(); j++) { try { // changes background colour of cell e.source.getActiveSheet().getRange(firstRow + i, firstColumn + j).setBackground(values[i][j]); } catch (e) { Logger.log(e); } } } // sets data validation setDataValidation(createColorList()); getColumnData(activeSpreadsheet); getFullColumn(columnIndex, startIndex); } } |
NOTE:
-
e.range 将是一个单元格,因此将只包含一个值。 -
因此,评估是否
var values = e.range.getValues();
和
e.source.getActiveSheet().getRange(firstRow + i, firstColumn + j).setBackground(values[i][j]);
说得通。 -
如果你只想改变编辑过的单元格的背景颜色,也许你可以使用
var value = e.range.getValue();
和
e.range.setBackground(value);