Reputation: 45
In a google sheet, I have a custom function in a cell =doSomething(myrange)
.
When using myrange
directly in my script, it will return the values of the range as an array. In case I need not the content of the range but the range itself (e.g. to get cell colors) there is an option to parse the first parameter as a string and produce the range on the fly.
Example:
function doSomething(myRange) {
let activeRg = SpreadsheetApp.getActiveRange();
let activeformula = activeRg.getFormula();
let countRangeAddress = activeformula.match(/\((.*)\,/).pop().trim();
...
Is there a more elegant way to retrieve the range and not the content of the range as an array? This would make the code much more readable.
Upvotes: 0
Views: 5044
Reputation: 2822
You could use a "named function" with a range
reference (e.g. = BGCOLORS(G125:H126)
) that calls your "custom function" with the "dimension" of rage
(e.g. =BACKGROUNDS(row,col,rows,cols)
Create a new "named function": "Data" ➜ "Named functions"
Define a "function name" and "formula definition" for it.
Function name: BGCOLOR
Formula definition: =BACKGROUNDS(ROW(range), COLUMN(range), ROWS(range), COLUMNS(range))
Change signature of your "custom function".
getRange(int,int,int,int)
function BACKGROUNDS(...args) {
const range = SpreadsheetApp.getActiveSheet().getRange(...args);
return range.getBackgrounds();
}
Use the "named function" in the Sheet. E.g. = BGCOLORS(G125:H126)
The combination of "named function" + "custom function" is very powerful. You can use native Sheets functions + custom Apps Script code bundled in a single function.
Upvotes: 1
Reputation: 5953
You can pass your range as a string in your custom function and use Sheet.getRange(a1Notation)
Instead of =doSomething(A2:B3)
use =doSomething("A2:B3")
Sample Code:
function doSomething(myRange){
var sheet = SpreadsheetApp.getActiveSheet();
var bgColors = sheet.getRange(myRange).getBackgrounds()
for (var i in bgColors) {
for (var j in bgColors[i]) {
Logger.log(bgColors[i][j]);
}
}
return bgColors;
}
Output:
Upvotes: 1