Google应用脚本可查找字符串并更改列背景颜色

时间:2017-04-07 16:44:33

标签: google-apps-script google-form

我有谷歌表格(谷歌电子表格)的结果。我想写一个应用程序脚本来检查每个列的字符串“是”。如果列具有该字符串,那么我想将该列的背景颜色(或该列中的一个单元格)更改为绿色。每次发送表单时列数都会有所不同,因此需要检查所有使用的列(对不起,我的意思是我每次发送一个类似的表单,并希望在每一个上使用相同的脚本,除了每次使用表单时,它都可以返回不同数量的列 - 响应 - 感谢corn3lius)。这可以在谷歌表格回复电子表格中完成吗?这是我正在玩的代码。 (使用Cooper的输入更新了代码)

function colchk(){
var ss = SpreadsheetApp.getActiveSheet();
var resp = ss.getDataRange().getValues();
for(var n=0;n<resp.length;n++)
{ 
for(var p=0;p<resp[n].length;p++)
{
if(resp[n][p].toString().match(/^YES/)){ ss.getRange(n+1,p+1).setBackground('#00ff00')}}};
}    
//this code works...Thanks Cooper!

4 个答案:

答案 0 :(得分:2)

这是一篇较旧的文章,但我想在这里为以后的访客留下一个更简单的解决方案:

function colorYesCells{
  var sheet = SpreadsheetApp.getActiveSheet(); 
  var yesFinder = sheet.createTextFinder("YES");
  var yesCells = yesFinder.findAll();
  
  yesCells.forEach(function(cell){
    cell.setBackground('#00ff00');
  });
};

答案 1 :(得分:1)

试试这个:

if(resp[n][0].toString().match(/^YES/){ ss.getRange(n+1,1).setBackground('#00ff00') };

Perhap是这样的:

function colchk(){
var ss = SpreadsheetApp.getActiveSheet();
var resp = ss.getDataRange().getValues();
for(var n=0;n<resp.length;++n)
{ 
  for(var p=0;p<resp[n].length;p++)
  {
    if(resp[n][p].toString().match(/^YES/){ ss.getRange(n+1,p+1).setBackground('#00ff00') };
  }
};

答案 2 :(得分:1)

由于我无法评论,我在这里写道:

for(var n=0;n<resp.length;++n)

应该是:

for(var n=0;n<resp.length;n++)

++ n - &gt;的n ++

打字太快了?

答案 3 :(得分:0)

基于@coopers代码 - 小编辑

function colchk(){
var ss = SpreadsheetApp.getActiveSheet();
var resp = ss.getDataRange().getValues();
for(var n=0;n<resp.length;n++)
{ 
  for(var p=0;p<resp[n].length;p++)
  {
    if(resp[n][p].toString().match(/^YES/)) { 
      ss.getRange(n+1,p+1).setBackground('#00ff00') };
  }
}};