Google Sheets获取背景颜色公式



我设置了这个自定义函数,它返回某个单元格的背景颜色:

/* Returns the Hexadecimal value of a cell's background color.
*
* @param {number} row The cell's row number.
* @param {number} column The cell's column number.
* @return The Hexadecimal value of the cell's background color.
* @customfunction
*/
function BGHEX(row, column) {
var background = SpreadsheetApp.getActive().getDataRange().getCell(row, column).getBackground();
return background;
}

起初它工作,但当我将脚本应用到按钮时,它开始抛出以下错误:

错误
异常:参数(null,null)不匹配的方法签名为SpreadsheetApp.Range.getCell.

有谁知道为什么它突然停止工作和如何解决它吗?

你可以这样做

function BGHEX() {
let r = SpreadsheetApp.getUi().prompt("Get Row and Column","Enter row , column",SpreadsheetApp.getUi().ButtonSet.OK);
let t  = r.getResponseText().split(',');
var background = SpreadsheetApp.getActiveSheet().getRange(t[0], t[1]).getBackground();
Logger.log(background);
return background;
}

或者选择单元格

function BGHEX() {
var background = SpreadsheetApp.getCurrentCell().getBackground();
Logger.log(background);
return background;
}

函数有两个参数,rowcolumn,这两个参数都是必需的,因为它们用作getCell参数。

要在按钮中使用这个,您必须以某种方式提供所需的参数:

  1. 提供默认值,
  2. 使用用户界面,即提示或对话框,要求用户输入参数

或者将单元格设置为与getBackground()一起使用,而不需要rowcolumn参数,即通过使用getActiveCell。

最新更新