get range from google sheets using r1c1 - google-apps-script

I want to get range selected from r1c1 r2c2
I have
var rc1 = '0:0-3:3';
//considering the string
var res = ss.getActiveSheet().getRange('R0C0:R3C3');
ss.getActiveSheet().setActiveSelection(res);
I get error Range not found

Your range is not found cause you trying to get element out of the table. R0C0 does not exist, R1C1 is the first existing element.
If you want to get range selected from R1C1 to R2C2, you've got
function getWithRCNotation(){
var ss=SpreadsheetApp.getActiveSpreadsheet();
var res = ss.getActiveSheet().getRange('R1C1:R2C2');
ss.getActiveSheet().setActiveSelection(res);
}

Make sure that you follow the instructions in this documentation. Based from this thread, when you pass a range, a1:d12 for example, to a function in gSheets, the values of the cells in that range are passed as an array. Try to pass it as a string, like =function("a1:d12"), and deal with the string notation for a range, ...getRange(stringargument).

Related

Google App Script - getFilter and getRange does not return desired filtered results

I have a filter applied to a sheet. I want to return just the data from the filter and not the entire range of the sheet.
const sheet = SpreadsheetApp.openById(SHEET_ID).getSheetByName(SHEET_NAME)
const filter = sheet.getFilter();
// This returns the entire sheet's range rather than the filtered range.
const range = filter.getRange().getValues();
Based on the code above, why aren't I getting the desired behaviour according to docs from Google?
I had a similar issue with returning filtered values and realized it is the most convenient to make a code that will skip FilterCriteriaBuilder class with functions.
For that reason I developed a code on this link.
https://github.com/NikolaPlusEqual/GoogleAppsScriptFilters/blob/main/Functions
Simple example for using functions from the repository:
function example(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ss1 = ss.getSheetByName("Sheet1");
var range = ss1.getRange(1,1,ss1.getLastRow(),5).getValues();
output = whenNumberGreaterThan(10, range, 3);
Logger.log(output);
}
whenNumberGreaterThan(number, rng, col) is the function from the repository, which will return all values from the rows in the range, that have satisfied "number greater than 10" criteria in the 3rd column of the range. The function is the alternative for FilterCriteriaBuilder Class function whenNumberGreaterThan(number) on this link.
Just copy entire Functions file code into you .gs file and call desired function.
You can get just the values the active filter displays by removing the values in the data that are in rows where isRowHiddenByFilter(rowPosition) returns true.
That said, using JavaScript's Array.filter() would offer much better performance than making multiple API calls to find which rows are hidden.

Google Sheets Apps Script, return random item from named range

I'm trying to create a custom function that I can give a name range as input and have it output a random item from the name range. I have multiple named ranges so it would be convenient to have one function that I could use for all of them. This is what I'm trying to replace =INDEX(named_range,RANDBETWEEN(1,COUNTA(named_range)),1)
This is what I've tried but it doesn't work:
function tfunction(n) {
var randomstuffs = SpreadsheetApp.getActiveSpreadsheet().getRangeByName(n);
var randomstuff = randomstuffs[Math.floor(Math.random()*randomstuffs.length)];
Logger.log(randomstuff);
}
Thanks in advance
You can try this edited script:
function tfunction(n) {
//randomstuffs will only get all cell data that are not empty from a named range
var randomstuffs = [].concat.apply([], SpreadsheetApp.getActiveSpreadsheet().getRangeByName(n).getValues()).filter(String);
var randomstuff = randomstuffs[Math.floor(Math.random()*randomstuffs.length)];
return randomstuff;
}
Sample Result
Created a sample named range TestRange on Column A with 21 cells of data then tried the custom function =tfunction("TestRange") which returned a random cell value.
.getRangeByName() method returns a reference to a range, not the values in the range. You need to add .getValues() to it:
var randomstuffs = SpreadsheetApp.getActiveSpreadsheet().getRangeByName(n).getValues();
Also keep in mind that .getValues() method returns a 2D array of values, indexed by row, then by column. So your var randomstuff declaration will need to be change to account for that, depending on how many rows and columns your range has.

google sheets script get cell contents

I have a list of URLs in a google spreadhseet and I want to get the cell reference to be used as a URL in the script.
An example of a URL I will be getting data from: https://politicsandwar.com/api/nation/id=31831
I want to do something like getValue.("O2") or var urlData = "O2" but I don't know how to go about getting to that point.
You should first get a range and then get its values.
var sheet = SpreadsheetApp.getActiveSheet();
//Gets all cell values form column "O" starting from row 2. Returns a 2d array
var wholeColumnUrls = SpreadsheetApp.getActiveSheet().getRange("O2:O").getValues();
//Gets value from specific cell "O2".
var singleCellUrl = SpreadsheetApp.getActiveSheet().getRange("O2").getValue();
There are multiple ways of defining a range, in this example we use the A1notation variant. Which seems to be what you're looking for.
Also, notice the difference between getValues() and getValue(). The first returns a 2d array like:
[
[https://politicsandwar.com/api/nation/id=31831]
,[https://politicsandwar.com/api/nation/id=31832]
,[https://politicsandwar.com/api/nation/id=31833]
]
while the latter returns a single value like https://politicsandwar.com/api/nation/id=31831
That way you can choose wether you get all the values and iterate over them, or have your own logic to determine each cell and get the values separately.

How to pass a range into a custom function in Google Spreadsheets?

I am trying to compare two google sheets (for duplicate values) over a predefined range..
I am aware that google lets you compare sheets via tools, but i need a more customized comparison hence the function.
I want to create a function which takes in a range... something like:
function myFunction(range) {
var firstColumn = range.getColumn();
// loop over the range
}
The problem is that when I try doing this, the parameter seems like it is only passing the values to the function. Thus, I cannot use any of the Range methods such as getColumn(). When I attempt to do so, it gives the following error:
error: TypeError: Cannot find function getColumn in object 1,2,3.
How can I send an actual range rather than just the values to one of my custom functions?
Note- Range in my case is the entire sheet (both of them that need to be compared).
Thanks!
Custom functions arguments are calculated before being passed to the code of the custom function so range will be a single value or an array of values.
You could pass a reference to a range as a string, i.e. =myFunction("Sheet!A:Z"), then use something like the following:
function myFunction(reference) {
var range = SpreadsheetApp.getActiveSpreadsheet().getRangeByName(reference);
var firstColumn = range.getColumn();
// do something
}
Note: getRangeByName work both with named ranges and references os it could be a better choice than getRange.
Google Script treats ranges as Arrays. So, you could better work with entered range as you work with an array. Here's good technique how to loop through an array:
https://stackoverflow.com/a/14991272/5372400
In your cell, you would do
=myFunction("A1")
Then in your code
function myFunction(ref)
{
var range = SpreadsheetApp.getActiveSpreadsheet().getRangeByName(ref);
// do something with range
}
getRangeByName is no longer used.
Source: https://developers.google.com/apps-script/reference/spreadsheet/sheet#getrangea1notation

Google Sheet Custom Function Not Recaculating

Hi I have read about the caching issues with custom functions in Google Sheets, but I'm trying to understand why the following will successfully update if a cell is changed:
function doob(input){
return input * 2;
}
but this will not update:
function doob(input){
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var range = sheet.getRange(input);
var values = range.getValues();
return values[0][0] * 2 ;
}
I need to get the range in order to use the .getBackgroundColor() of each cell.
Probably because in the first function you would pass the cellreference directly,
=doob(A1)
and in the script the value of that cell is used.
In the second, you would probably have to pass the range as string (since you want to get the backgroundcolors, so you are not after the values of that range, right ?)
=doob("A1:B8")
As you know, custom functions suffer from memoization. To work around that you could pass in the range a second time, without the quotation marks.
=doob("A1:B8", A1:B8)
That second paramater is a 'dummy' paramater as the script does nothing with it. BUT: any change in values in that range should make the custom function re-evaluate. However I don't know if that is gonna help you a lot if your final goal is to get the backgroundcolors.