0

我一直在寻找我需要做的事情,但我无法弄清楚如何从之前发布的文章中完成此操作。当一个单元格具有特定值时,Google脚本应用会更改颜色单元格

我有这样的谷歌电子表格here

想我喜欢做的事就是在analize所谓的‘实际’工作表中的数据,并设置单元格的背景颜色,当满足条件的情况。所以基本上,我正在寻找一个脚本来做到这一点:

get the data from the sheet called 'actual' 
if a cell is error (equals to "#N/A") then set the color font to white 
if a cell equals to "wnd" then set the background color to "red" 
if the cell equals to "otc", then set the background color to "green" 
etc.. 

这将有大约50的条件,这就是为什么我喜欢的代码要做到这一点,而不是常规的条件格式。

预先感谢您。

回答

0

更改您的代码,以尽量减少使用得到调用。这些都是很慢的电话。所以你想采取一个大的。然后处理所有的数据。以下是一些示例代码:

注意此函数检查值为3并将它们设置为红色背景,并用白色文本。其工作的当前范围在无功范围内定义。根据需要自行设置。

function setCellColors() { 
    //Get the sheet you want to work with. 
var ss = SpreadsheetApp.getActiveSpreadsheet(); 
var sheet = ss.getActiveSheet(); 
    //Grab the entire Range, and grab whatever values you need from it. EX: rangevalues 
var range = sheet.getRange("A1:E17"); 
var rangevalues = range.getValues(); 
    //Loops through range results 
for (var i in rangevalues) { 
    for (var j in rangevalues) { 
    //Get the x,y location of the current cell. 
     var x = parseInt(j, 10) + 1; 
     var y = parseInt(i, 10) + 1; 
    //Set the rules logic 
    if (rangevalues[i][j] == 3) { 
     //Set the cell background 
     sheet.getRange(y,x).setBackground("red"); 
     sheet.getRange(y,x).setFontColor("white"); 
    } 
    } 
    } 
} 
+0

这看起来非常好。你能解释一下为什么你在这些变量中使用10作为第二个参数:var x = parseInt(j,10)+ 1; var y = parseInt(i,10)+ 1; –

+0

我已经使用你的代码来做到这一点,我已经更新了var range来做我需要的。但是,我只能得到结果,直到列O.我更新了谷歌电子表格,以此代码作为示例,以便您可以查看它。我只是无法弄清楚为什么只能工作到O列。预先感谢您。 –

+0

10是您要解析的数字的基础。如果你想要二进制,它将是不同的,或十六进制数字,等等。要更新电子表格以包含更多列,请更改范围变量。您可以动态或静态地显示此显示。如果你想要它是静态的,只需像我一样选择值。如果你想动态地使用它,那么你必须写入它(如果有帮助,请记得选择一个答案,这样未来的搜索者可以更容易地找到它) –

0

希望this helps.

function setCellColors() { 
//Get the sheet you want to work with. 
var ss = SpreadsheetApp.getActiveSpreadsheet(); 
var sheet = ss.getActiveSheet() 
    // determine how how big your data range will be 
var lastColumn = sheet.getLastColumn() + 1 
var lastRow = sheet.getLastRow() + 1 
    // iterate through the data. 
for (var column = 1; column < lastColumn; column++) { 
    for (var row = 1; row < lastRow; row++) { 
     var cellget = sheet.getRange(row, column).getValue(); 
     var cellset = sheet.getRange(row, column); 
     //Set the rules logic 
     if (cellget === "#N/A") { 
      //Set the cell background 
      cellset.setBackground("red"); 
      cellset.setFontColor("white"); 


     } 
    } 
} 
} 
+0

它确实有帮助!非常感谢你。 –

+0

当运行代码时,我得到这个执行提示:方法Range.getValue被脚本大量使用。收起 文件:代码行:11 该脚本使用一种被认为是昂贵的方法。每次调用都会产生一个耗时的远程服务器调用。这可能会对脚本的执行时间产生严重影响,尤其是对于大数据。如果性能是脚本的问题,则应考虑使用其他方法,例如Range.getValues()。我不确定如何使用Range.getValues()方法。 –

+0

当要评估的行数增加时,我收到以下消息:超出最大执行时间。 –

相关问题