Reputation: 233
I'm trying to create a custom formula for Google Sheets using Apps Script. The function will return the Hexadecimal background color of the cell (e.g. =getHEX(B1)
will return the color of cell B1).
My problem is that I can bring the value of the cell, not the location. If I use quotes in the function it works (=getHEX("B1")
) but I wonder how can I avoid using the quotes and still get the value of the cell.
I tried to use the A1Notation function and it supposedly bring the location (B1) but when added to the function I still get the same error (Range not found). Below is the function as a reference:
function getHEX(cellReference) {
const getCell = SpreadsheetApp.getActiveSheet().getRange(cellReference.toString()).getBackground();
return getCell;
}
Upvotes: 0
Views: 1932
Reputation: 1384
Following Marios' Answer, I'd like to add a solution 3 which does simplify the function like OP asked.
I basically had the same issue where I wanted to just pass the cell as a range instead of a value and went with:
function cell_getBackground(cell_address) {
var bg = SpreadsheetApp.getActive().getRange(cell_address).getBackground();
return bg;
}
On the spreadsheet page: Data > Named Functions > Add new function >
Function name:getHEX
Argument placeholders:cellRef
Formula definition:=cell_getBackground(cell("address", cellRef))
=getHEX(B1)
Upvotes: 1
Reputation: 27350
=getHEX(B1)
would pass directly the value, and not the actual range that is used in google apps script to get the background.Solution 1:
Google Apps Script:
function getHEX(cellReference) {
const getCell = SpreadsheetApp.getActiveSheet().getRange(cellReference).getBackground();
return getCell;
}
Google Sheets:
=getHEX(ADDRESS(row(E4),column(E4),4))
to get the background color of cell E4
. You can also drag down the formula in this way.
Solution 2:
Use the coordinates directly but structure the function to accept two arguments (x and y).
Google Apps Script:
function getHEX(x,y) {
const getCell = SpreadsheetApp.getActiveSheet().getRange(x,y).getBackground();
return getCell;
}
Google Sheets:
=getHEX(row(E4),column(E4))
Upvotes: 2