首页 > 解决方案 > 是否可以通过搜索列名以条件格式动态插入自定义公式?

问题描述

我正在尝试在 google 脚本中构建一个函数,该函数允许我在某些列名中进行编码(因为这些将保持不变),并让该函数按名称查找该列,并通过条件创建/插入自定义公式格式化以突出显示该列中的重复项。查找重复项的公式为 =COUNTIF(E:E,E1)>1(以 E 列为例)。

所以重申一下,我想做的是:

  1. 具有插入新条件格式规则以突出显示连续重复项的功能
  2. 如果列在数据集之间移动,则新条件格式的公式是动态的(尽管列名相同)
  3. 让此函数按名称而不是数字将条件格式插入列中

我试图在 stackoverflow 上找到类似的东西,但没有找到太多的运气,只有几篇文章:

条件格式规则生成器脚本中的自定义公式

通过列名而不是列索引获取列值

所以这张表会找到“WOW”列:

条件格式之前的工作表

期望的结果/函数运行后看起来像这样(突出显示 WOW 列中的 E2 和 E2):

条件格式化后的工作表

所以我尝试制作这段代码如下,但是我希望有人有更好的主意,因为它不太好用,而且这似乎是高级编码(我是新手)

function conditionalformat1(){
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('sheet1');//need to call the tab name as I have many tabs
  var colName = 'WOW' //specific column name to have this function search for
  var sheetName = 'sheet1'

  var newRule = SpreadsheetApp.newConditionalFormatRule()
                    .whenFormulaSatisfied('=COUNTIF(E:E,E1)>1')//this should be dynamic instead what it is now...not sure if we can use R1C1 notation?
                    .setBackground('red')
                    .setRanges(getColByName)
                    .build()

  var rules = sheet.getConditionalFormatRules();
  rules.push(conditionalformat1);
  sheet.setConditionalForatRules(rules);

function getColByName(colName) {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('sheet1');
  var colName = 'WOW'
  var data = sheet.getRange("1:1000").getValues();//have it search the entire sheet?
  var col = data[0].indexOf(colName);
  if (col != -1) {
    return data[row-1][col];
  }
}



}//end of conditionalformat1 conditional formatting

提前感谢您的帮助,这将有助于学习如何让函数按名称查找列并执行项目。

标签: javascriptgoogle-apps-scriptgoogle-sheets

解决方案


您不需要任何代码,只需使用条件格式公式

=AND(a$1="WOW";countif(A$2:A;a2)>1)

在此处输入图像描述


推荐阅读