Search code examples
javascriptgoogle-apps-scriptgoogle-sheetscustom-function

Google Sheets get Background color formula


I set up this custom function that returns the background color of a certain cell:

/* 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;
}

At first it worked, but when I applied the script to a button, it started throwing the following mistake:

Error
Exception: The parameters (null,null) don't match the method signature for SpreadsheetApp.Range.getCell.

Any one has an idea of why it stopped working all of a sudden and how to fix it?


Solution

  • You might be able to do it like this

    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;
    }
    

    or this way by selecting the cell

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