如果文本被另一个单元格匹配,请使用Google Apps脚本有条理地格式化一个单元格

时间:2018-04-05 22:09:14

标签: google-apps-script google-sheets

我有一个电子表格,其前四列(A,B,C,D)是从单独的主电子表格中动态导入的。

列E,F旨在根据左侧列中的动态数据获取静态输入。

A栏包含个人姓名。

我想使用G列作为A列的静态参考,以确保E&列中的输入。当A / D列中的动态数据随着新输入从主表单到达或从主表单中删除时,F可以通过手动剪切和粘贴轻松保存在正确的行中。

要做到这一点,我想要一个有条件地格式化的脚本' G列中的条目与A列中的条目匹配(粗体,斜体,颜色文本),并且不会与使用Google工作表中的标准UI条件格式切割和粘贴相关的问题发生冲突,其中剪切和粘贴会破坏'条件格式化范围。

我们将动态列A中的值复制到静态列G,然后使用条件格式引用回A。

我这里有一个基本脚本(从另一个stackoverflow海报中收集),但是需要做一些工作来完成我需要做的事情。

function onEdit() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange("A:G");
var values = range.getValues();

//for each row that data is present
for(var i = 0; i < values.length; i++) {
var cell = sheet.getRange(i + 1, 7);

//check if the first value of that row is exactly "Client Name"
if(values[i][0] === "Client Name") {

//if it is, check for "Client Name" in the same row in G [6].  If so, make 
it green.

if(values[i][6] === "Client Name") {
    cell.setBackground('green');
  } else {
    cell.setBackground('white');
  }

} else {

//In any other case, make it white.
cell.setBackground('white');
}
}   
}    

我希望脚本检查单元格A3:A中的值是否等于G3中的值:G以及是否要格式化G3:G中的文本。

A&#34;模拟&#34;现有脚本的工作表在这里:

https://docs.google.com/spreadsheets/d/13iPM83I5ecskuBaBin8hepTyBqD29ng0Zp3e6DBcuEk/edit?usp=sharing

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

如果您将条件格式设置为使用自定义公式

=AND($G1=$A1, NOT(ISBLANK($A1)))

然后您使用“仅粘贴值”(编辑&gt;粘贴特殊或cmd + shift + vctrl如果在Windows上),那么您将不需要脚本。

使用条件格式和粘贴值会快得多。

否则,当它与A中的相应值不匹配时,您可以使用此脚本更改G列中的格式。

function onEdit() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Sheet1"); // getActiveSheet() can yield unexpected results
  var rangeA = sheet.getRange("A:A");
  var rangeG = sheet.getRange("G:G");
  var valuesA = rangeA.getValues();
  var valuesG = rangeG.getValues();
  var backgrounds = []; // Create an array for the background colors
  var fontColors = []; // Create an array for the font colors

  //for each row that data is present
  for(var i = 0; i < valuesA.length; i++) {
    var aValue = valuesA[i][0];
    var gValue = valuesG[i][0];
    if((aValue != "") && (gValue === aValue)) { // If value in A is NOT blank AND A == G
      backgrounds.push(["green"]); 
      fontColors.push(["white"]);
    } else {
      backgrounds.push([null]); // Using null will reset the background color formatting
      fontColors.push([null]); // Using null will reset the font color formatting
    }
  }  
  rangeG.setBackgrounds(backgrounds); // Set the background colors all at once for speed.
  rangeG.setFontColors(fontColors); // Set the font colors all at once for speed.
}
相关问题