Google Sheets自定义函数条件格式

Google Sheets custom function conditional formatting

本文关键字:格式 条件 自定义函数 Sheets Google      更新时间:2023-09-26

如果单元格的值等于上面两行单元格的值,我需要使单元格文本变红。我的脚本编辑器中有以下两个函数:

/**
 * Compares cell value to another cell relative in position to it.
 * Returns true if equal values.
 *
 * @param {Number} colDiff Relative positioning column difference.
 * @param {Number} rowDiff Relative positioning row difference.
 */
function equalsRelativeCellValue(rowDiff, colDiff) {
  var thisCell = SpreadsheetApp.getActiveRange();
  var relativeCellValue = getRelativeCellValue(rowDiff, colDiff);
  if (thisCell.getValue() === relativeCellValue)
    return true;
  else
    return false;
}

/**
 * Returns value of cell according to relative position
 *
 * @param {Number} colDiff Relative positioning column difference.
 * @param {Number} rowDiff Relative positioning row difference.
 */
function getRelativeCellValue(rowDiff, colDiff) {
  var range = SpreadsheetApp.getActiveRange();
  var col = range.getColumn();
  var row = range.getRow();
  var range2 = SpreadsheetApp.getActiveSheet().getRange(row + rowDiff,col + colDiff);
  return range2.getValue();
}

第二个函数,getRelativeCellValue(rowDiff, colDiff)工作得很好,我把8放在一个单元格中,在它下面的两个单元格中我输入了getRelativeCellValue(-2, 0),单元格计算为8

但是第一个函数getRelativeCellValue(rowDiff, colDiff)由于某种原因不能作为条件格式中的自定义函数:

Custom formula is: =equalsRelativeCellValue(-2,0)

困难的部分是引用条件格式中引用的单元格的值。但我的函数看起来很对,如果单元格值相等,它将返回true,如果不相等,则返回false。我希望我只是不恰当地使用了条件格式的"自定义公式"功能,但文档相当稀疏。

只需重新分配您想要做的事情,只需使用条件格式,选择范围,并应用于第一个单元格,它将正确应用于所有单元格:

例如。在条件格式设置对话框中,选择"自定义公式",粘贴自定义公式=J10=J8,然后选择范围J10:J100

旧答案:

您创建了一个循环引用。

如果你在单元格中输入=equalsRelativeCellValue(-2,0),如果它正在等待函数解析,它的值怎么可能是任何东西?

您可以在值之外的列中克服这一点,也可以直接在函数中传递值。

您也可以使用它来使单元格之间的状态为真/假:

function equalsRelativeCellValue(rowDiff, colDiff) {
  var below = getRelativeCellValue(1, 0);
  var relativeCellValue = getRelativeCellValue(2, 0);
  if (below === relativeCellValue)
    return true;
  else
    return false;
}