Dom*_*Dom 8 google-apps-script
我正在Google表格上使用此Google App脚本进行操作,该功能是由时间驱动的触发器运行的。我希望能够定位工作表上的特定单元格(如果单元格值=“打开”),以便可以更改单元格的背景色。我想知道如何进行这项工作?我可以锁定单元格,但是我不知道如何更改单元格背景的属性,因为无法调用.setBackground()。
function myColorFunction() {
var s = SpreadsheetApp.getActiveSheet();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var range = ss.getSheetByName("Form Responses 1").getRange(2,6,ss.getLastRow());
var cellRange = range.getValues();
Logger.log(cellRange);
Logger.log(cellRange.length);
Logger.log(cellRange.valueOf());
for(i = 1; i<cellRange.length; i++){
if(cellRange[i] == "Open")
{
Logger.log("change color here");
} else {
Logger.log("don't change color");
}
}
}
Run Code Online (Sandbox Code Playgroud)
修改
自从引入V8 运行时,就可以利用现代 ES6 特性,例如箭头函数和解构。此外,可以优化脚本以避免它在较大的集合上变慢。
首先,遵循最佳实践很重要。I/O(输入/输出)操作,例如getRange、setBackground、setValue很慢。不要使用这些内部循环,使用批处理操作一样getBackgrounds,setBackgrounds,setValues,setFontColors,等。
其次,处理值网格比每次需要转到另一行时偏移范围要快得多。链接getDataRange并getValues从工作表中获取所有值并直接处理结果数组(如果工作表中有大量数据,请getRange根据自己的喜好使用 ,只需遵循相同的原则)。
最后,硬编码表名称使脚本不灵活,它应该是函数的参数,或者至少是函数可访问的上下文中的声明常量。
片段
鉴于上述修改,(另一个答案的)片段可以修改如下:
const myColorFunction = ({
sheetName = "Form Responses 1",
targetValue = "Open"
} = {}) => {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName(sheetName);
const rng = sheet.getDataRange();
const numHeaders = 1;
const backgrounds = rng.getBackgrounds();
const fontColors = rng.getFontColors();
const newBckgs = backgrounds.map((row) => {
const [firstCell] = row;
if (firstCell === targetValue) {
row[5] = "red";
}
return row;
});
const newColors = fontColors.map((row) => {
const [firstCell] = row;
if (firstCell === targetValue) {
row[5] = "white";
}
return row;
});
rng.setBackgrounds(newBckgs);
rng.setFontColors(newColors);
}
Run Code Online (Sandbox Code Playgroud)
笔记
map调用,但我将它们分开是为了更清晰的流程并避免改变
backgrounds或fontColors数组。"red"和"white"以及要设置颜色的列的索引。您可以将setBackground属性与一起使用getRange。试试下面的代码片段。
function myColorFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var range = ss.getSheetByName("Form Responses 1").getRange(2,6,ss.getLastRow());
var cellRange = range.getValues();
for(i = 0; i<cellRange.length-1; i++){
if(cellRange[i][0] == "Open")
{
ss.getSheetByName("Form Responses 1").getRange(i+2,6).setBackground("red");
ss.getSheetByName("Form Responses 1").getRange(i+2,6).setFontColor('white');
}
}
}
Run Code Online (Sandbox Code Playgroud)