I have a GoogleSheet with basically two sheets, which are very similar in terms of data collected.
I need to calculate same values for both sheets, but source data is in different columns.
Therefore I created three files in AppsScript:
Common.gs - with common function definitions
sheet1.gs
sheet2.gs - both sheet1 and sheet2 have only definitions of proper ranges in particular columns and one function to run script, which essentially calls functions defined in Common.gs, like so in sheet1.gs:
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("sheet1")
var createdColumn = sheet.getRange("E2:E").getValues()
var ackColumn = sheet.getRange("G2:G").getValues()
var resColumn = sheet.getRange("I2:I").getValues()
var timeToAckColumn = sheet.getRange(2,14,ackColumn.length,1)
var timeToResColumn = sheet.getRange(2,15,resColumn.length,1)
var yearAndWeekRange = sheet.getRange(2,16,createdColumn.length,2)
function calculateMetricsSheet1() {
calculateTimeDiff(createdColumn, ackColumn, timeToAckColumn)
calculateTimeDiff(ackColumn, resColumn, timeToResColumn)
calculateWeek(createdColumn, yearAndWeekRange)
}
example function implementation (they are basically very similar with minor differences):
function calculateWeek(createdColumn, yearAndWeekRange) {
var arrData = []
for(var i=0;i<createdColumn.length;i++) {
if(createdColumn[i][0].toString()=="") {
arrData.push(["",""])
continue
}
var createdDate = new Date(createdColumn[i][0])
var year = createdDate.getFullYear()
var week = Utilities.formatDate(createdDate, "GMT+1", "w")
arrData.push([year, week])
}
yearAndWeekRange.setValues(arrData)
}
the sheet2.gs is basically different column definitions, the functions called within calculateMetricsSheet2() are the same.
So what is the problem?
The script works perfectly fine for sheet2.gs, but for sheet1.gs it does collect proper data, calculates proper data, but the data does not appear in proper columns after Range.setValues() call.
No exceptions or errors appear in the console.
Documentation does not provide any kind of information what could be the problem.
I have really ran out of ideas what could be the cause of the issue.
Does anyone have any idea what is going on?
edit: It may be useful to put emphasis on the fact that each script runs function calling 3 other functions -> all of them end with Range.setValues({values}). And for one sheet all of them work, and for the other - none.
That's the reason I assume there is something wrong with the sheet itself, maybe some permissions/protection? But I couldn't find anything :(
edit2: I modified my code to iterate through the sheet 10 rows at a time, because I thought maybe when I get a whole column, something bad happens with data and breaks setValues() function.
Unfortunately - even if my code iterated 1 row at a time, it still did not work on sheet1, but worked on sheet2. So not a data problem.
The code you show always puts values in yearAndWeekRange which is always in the 'sheet1' sheet. To put the data into another sheet, you need to change the target range appropriately.
The dimensions of the range must match the dimensions of the array you put there. Use this pattern:
yearAndWeekRange.offset(0, 0, arrData.length, arrData[0].length).setValues(arrData);
I found out what is the problem.
Two scripts were pretty identical, even with naming of variables - ie ackColumn, resColumn etc.
Those were stored as a global variables, so even if I was running script1.gs, it used global variables from script2.gs, effectively writing proper data to wrong sheet.
separating global variables names fixed the issue.
Perhaps a rookie mistake, but I missed the fact, that if I have a variable defined outside any function, it becomes global and could be overwritten from other file
I have a .tsv file from a tool and I have to import it the Google Sheet (nearly) real-time for reports. This is my code for importing:
function importBigTSV(url) {return Utilities.parseCsv(UrlFetchApp.fetch(url).getContentText(),'\t');}
It worked till some days ago when Error messages keep saying "Exceeded maximum execution time (line 0)."
Could anyone help? Thank you a lot!
Issue:
As #TheMaster said, custom functions have a hard limit of 30 seconds, which your function is most probably reaching. Regular Apps Script executions have a much more generous time limit (6 or 30 minutes, depending on your account), so you should modify your function accordingly.
Differences between functions:
In order to transform your function, you have to take into account these basic differences:
You cannot pass parameters to a function called by a Menu or a button. Because of this, you have to find another way to specify the URL to fetch.
Values returned by a regular function don't get automatically written to the sheet. You have to use a writing method (like setValues, or appendRow) to do that.
A non-custom function is not called in any particular cell, so you have to specify where do you want to write the values to.
Since, from what I understand, you are always fetching the same URL, you can specify that URL just by hardcoding it into your function.
Solution:
The function below, for example, will write the parsed output to the range that is currently selected (at the moment of triggering the function). You could as well provide a default range to write the output to, using getRange:
function importBigTSV() {
var url = "{url-to-fetch}";
var range = SpreadsheetApp.getActiveRange();
try {
var output = Utilities.parseCsv(UrlFetchApp.fetch(url).getContentText(),'\t');
var outputRange = range.offset(0, 0, output.length, output[0].length);
outputRange.setValues(output);
} catch(err) {
console.log(err);
}
}
If the URL can change, I'd suggest you to have a list of URLs to fetch, and, before triggering the function, select the desired URL, and use getActiveRange in order to get this URL.
Attaching function to Menu:
In any case, once you have written your function, you have to attach this function somehow, so that it can be trigged from the sheet itself. You can either create a custom menu, or insert and image or drawing, and attach the script to it. The referenced links provide clear and concise steps to achieve this.
Reference:
Custom Functions > Return values
Custom Menus in G Suite
I've been using this function to shorten links (Get range, if length over 200, copy and paste over new tinyurl link in same cell). But I wanna modify it to take active cell or active range instead of input range from UI prompt response. In this case I probably wouldn't need the if(x.length > 200) condition either. I've tried to research for some solutions that I could implement but its too complex for my beginner skills and understanding of original code to modify. Is there an easy fix I could do to it?
function tinyUrl() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ui = SpreadsheetApp.getUi();
var final = [];
var response = ui.prompt('Enter range:');
if(response.getSelectedButton() == ui.Button.Ok) {
try{
var values = [].concat.apply([], ss.getRange(response.getResponseText()).getValues()).filter(String);
SpreadsheetApp.getActiveSpreadsheet().toast('Processing range: '+ss.getRange(response.getResponseText()).getA1Notation(),'Task Started');
values.forEach(x => {
if(x.length > 200) {
final.push(["IMPORTDATA(concatenate(\"http:// tiny url.com/api-create.php?url="+x+"\"),\"\")"]);
}else{
final.push(["=HYPERLINK(\""+x+"\")"]);
}
})
}catch(e){
SpreadsheetApp.getUi().alert(response.getResponseText()+' is not valid range!');
}
}else{
return;
}
var r = response.getResponseText().split(":");
if(r[0].length=1 &&r[1].length == 1){
ss.getRange(r[0]+"1:"+r[0]+final.lenght).setFormulas(final);
}else{
ss.getRange(r[0]+":"+r[0].slice(0,1)+final.length).setFormulas(final);
}
}
The exact solution depends on your actual application. I think your question is how to detect where to apply your custom function. But let's take a step back.
There are two ways to interact with existing data in sheet and a custom function via AppsScript.
One is that you can directly call your custom function with ranges in the sheet. If the input range is a single cell, the data is read directly. If the input range spans more than a single cell, the data is read as nested lists: a list of columns which are lists of rows. For example, A1:B2 will be read as [[A1, B1], [A2, B2]].
So, for example, you can always call your custom function tinyurl() wherever you input url in your sheet and let your custom function decide when to shorten it. Since your custom function is called in-place, there is no detection issue; UI prompt is not required.
The downside is that if you call your custom function in too many places, there will be delay in getting results. And I don't think the results are always stored with the sheet. (ie. when you open the sheet again, all cells with tinyurl() may refresh and cause delay.)
Second method is via the Range Class which is what you are using. Instead of using UI prompt though, you can add onEdit() trigger to your custom function and let your function either check for currently selected cell via SpreadsheetApp.getActive().getActiveRange() or scan for urls over the sheet where you intend for user inputs to be stored.
The downside of using onEdit() trigger is the UI lag. Relying on actively selected range can also be problematic. Yet if you scan over the whole sheet, well, you have to do that. At the end though, you get to store the resultant URLs permanently with the sheet. So after the initial lag, you won't have delays in the future.
In this route, you may find getLastRow(), getLastColumn() in Sheet and getNextDataCell() in Range convenient. If you choose to process the whole sheet, you may instead use the onOpen() trigger.
I would prefer to store all URLs in one place and use the 1st option. Thus, the custom function is only called once and that's useful for minimizing delay. Other parts of the sheet can reference cells in that centralized range.
The exact solution depends on your actual application.
I just discovered Google App Scripts, and I'm stumped on something already...
I am trying to write a script for a Google Spreadsheet which finds certain historical stock prices. I found that the FinanceApp service within Google App Scripts has been deprecated, and seemingly replaced by the GOOGLEFINANCE() function within Google Spreadsheets. However, it returns an array, when I need only a single cell, and the array is mucking up the works.
So I'd like to write a short script that calls the GOOGLEFINANCE() spreadsheet function, and finds just the 1 piece of info I need from the array which is returned by GOOGLEFINANCE(). However, I cannot find a way to access Spreadsheet Functions (SUM, VLOOKUP, GOOGLEFINANCE, etc) within a script.
Is there a way to access these functions in a script? Or perhaps, is there a new service which replaces the deprecated FinanceApp service?
Many thanks for any assistance!
You can try this:
var trick = SpreadsheetApp.getActiveSheet().getRange('D2').setValue('=GOOGLEFINANCE("GOOG")').getValue();
Native Spreadsheet functions are not supported in Google Apps Script.
You could eventually use a somewhat cumbersome workaround by reading the value of a cell in which you write a formula (using script in both write and read) but this will be less than practical and / or fast.
You might try the INDEX function combined with GOOGLEFINANCE-
For reference,
=GOOGLEFINANCE("MSFT", "PRICE", "01/01/21")
Returns the array:
Date Close
1/4/2021 217.69
One can add the INDEX function to pick out specific elements from the array using the row,column coordinates of the array.
=INDEX(GOOGLEFINANCE("MSFT", "PRICE", "01/01/21"),2,2)
This returns just the data in row 2, column 2 - 217.69
There is one possible way, with the .setFormula(). This function behave like .setValue() and can be used the following way:
var ss = SpreadsheetApp.getActiveSpreadsheet();
var mySheet = ss.getSheets()[0]
//Code Below selects the first cell in range column A and B
var thisCell = mySheet.getRange('A:B').getCell(1,1);
thisCell.setFormula('=SUM(A2:A4)');
All formulas you write in this function are treated as strings must have ' or " within the .setFormula() input.
I've written a custom Google Apps Script that will receive an id and fetch information from a web service (a price).
I use this script in a spreadsheet, and it works just fine. My problem is that these prices change, and my spreadsheet doesn't get updated.
How can I force it to re-run the script and update the cells (without manually going over each cell)?
Ok, it seems like my problem was that google behaves in a weird way - it doesn't re-run the script as long as the script parameters are similar, it uses cached results from the previous runs. Hence it doesn't re-connect to the API and doesn't re-fetch the price, it simply returns the previous script result that was cached.
See more info here(Add a star to these issues, if you're affected):
https://issuetracker.google.com/issues/36753882
https://issuetracker.google.com/issues/36763858
and Henrique G. Abreu's answer
My solution was to add another parameter to my script, which I don't even use. Now, when you call the function with a parameter that is different than previous calls, it will have to rerun the script because the result for these parameters will not be in the cache.
So whenever I call the function, for the extra parameter I pass "$A$1".
I also created a menu item called refresh, and when I run it, it puts the current date and time in A1, hence all the calls to the script with $A$1 as second parameter will have to recalculate. Here's some code from my script:
function onOpen() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var entries = [{
name : "Refresh",
functionName : "refreshLastUpdate"
}];
sheet.addMenu("Refresh", entries);
};
function refreshLastUpdate() {
SpreadsheetApp.getActiveSpreadsheet().getRange('A1').setValue(new Date().toTimeString());
}
function getPrice(itemId, datetime) {
var headers =
{
"method" : "get",
"contentType" : "application/json",
headers : {'Cache-Control' : 'max-age=0'}
};
var jsonResponse = UrlFetchApp.fetch("http://someURL?item_id=" + itemId, headers);
var jsonObj = eval( '(' + jsonResponse + ')' );
return jsonObj.Price;
SpreadsheetApp.flush();
}
And when I want to put the price of item with ID 5 in a cell, I use the following formula:
=getPrice(5, $A$1)
When I want to refresh the prices, I simply click the "Refresh" -> "Refresh" menu item.
Remember that you need to reload the spreadsheet after you change the onOpen() script.
You're missing the fastidious caching bug feature. It works this way:
Google considers that all your custom functions depend only on their parameters values directly to return their result (you can optionally depend on other static data).
Given this prerequisite they can evaluate your functions only when a parameter changes. e.g.
Let's suppose we have the text "10" on cell B1, then on some other cell we type =myFunction(B1)
myFunction will be evaluated and its result retrieved. Then if you change cell B1 value to "35", custom will be re-evaluated as expected and the new result retrieved normally.
Now, if you change cell B1 again to the original "10", there's no re-evaluation, the original result is retrieved immediately from cache.
So, when you use the sheet name as a parameter to fetch it dynamically and return the result, you're breaking the caching rule.
Unfortunately, you can't have custom functions without this amazing feature. So you'll have to either change it to receive the values directly, instead of the sheet name, or do not use a custom function. For example, you could have a parameter on your script telling where the summaries should go and have an onEdit update them whenever a total changes.
What I did was similar to tbkn23. This method doesn't require any user action except making a change.
The function I want to re-evaluate has an extra unused parameter, $A$1. So the function call is
=myFunction(firstParam, $A$1)
But in the code the function signature is
function myFunction(firstParam)
Instead of having a Refresh function I've used the onEdit(e) function like this
function onEdit(e)
{
SpreadsheetApp.getActiveSheet().getRange('A1').setValue(Math.random());
}
This function is triggered whenever any cell in the spreadsheet is edited. So now you edit a cell, a random number is placed in A1, this refreshes the parameter list as tbkn23 suggested, causing the custom function to be re-evaluated.
There are settings where you can make NOW() update automatically:
If your custom function is inside a specific column, simply order your spreadsheet by that column.
The ordering action forces a refresh of the data, which invokes your custom function for all rows of that column at once.
Script Logic:
Custom Functions don't update unless it's arguments changes.
Create a onChange trigger to change all arguments of all custom functions in the spreadsheet using TextFinder
The idea to add a extra dummy parameter by #tbkn23 and use of the triggers by #Lexi Brush is implemented here with a random number as argument. This answer mainly differs due to usage of class TextFinder(a relatively new addition to Apps script), which is better because
No extra cell is required.
No menu is needed > No additional clicks needed. If you need a custom refresher, a checkbox is a better implementation
You can also change the formula itself instead of changing the parameters
The change/trigger can be configured to filter out only certain changes. For eg, the following sample script trigger filters out all changes except INSERT_GRID/REMOVE_GRID(Grid=Sheet). This is appropriate for the custom function that provides sheetnames. A edit anywhere isn't going to change the list of sheets/sheetnames, but inserting or removing sheet does.
Sample custom function(to refresh):
/**
* #customfunction
* #OnlyCurrentDoc
* #returns Current list of sheet names
*/
const sheetNames = () =>
SpreadsheetApp.getActive()
.getSheets()
.map((sheet) => sheet.getName());
Refresher function:
/**
* #description Automatically refreshes specified custom functions
* #author TheMaster https://stackoverflow.com/users/8404453
* #version 2.0.0
* #changelog
* Updated to support all custom functions and arguments
* Avoid eternal loops
*/
/**
* #listens to changes in a Google sheet
* #see https://developers.google.com/apps-script/guides/triggers/installable#managing_triggers_manually
*/
function onChange(e) {
/* Name of the custom function that is to be refreshed */
const customfunctionName = 'SHEETNAMES',
regexPattern = `=${customfunctionName}${String.raw`\(([^)]*?)?(?:,\s*?"RANDOM_ID_\d+")?\)`}`,
replacementRegex = `=${customfunctionName}${String.raw`($1,"RANDOM_ID_${
Math.floor(Math.random() * 500) + 1
}")`}`;
/* Avoid eternal loop
* Increase timeout if it still loops
*/
const cache = CacheService.getScriptCache(),
key = 'onChangeLastRun',
timeout = 5 * 1000 /*5s*/,
timediff = new Date() - new Date(JSON.parse(cache.get(key)));
if (timediff <= timeout /*5s*/) return;
cache.put(key, JSON.stringify(new Date()));
/* Following types of change are available:
* EDIT
* INSERT_ROW
* INSERT_COLUMN
* REMOVE_ROW
* REMOVE_COLUMN
* INSERT_GRID
* REMOVE_GRID
* FORMAT
* OTHER - This usually refers to changes made by the script itself or sheets api
*/
if (!/GRID|OTHER/.test(e.changeType)) return; //Listen only to grid/OTHER change
SpreadsheetApp.getActive()
.createTextFinder(regexPattern)
.matchFormulaText(true)
.matchCase(false)
.useRegularExpression(true)
.replaceAllWith(replacementRegex);
}
To Read:
Installable triggers
TextFinder
As noted earlier:
Custom Functions don't update unless it's arguments changes.
The possible solution is to create a checkbox in a single cell and use this cell as an argument for the custom function:
Create a checkbox: select free cell e.g. [A1], go to [Insert] > [Checkbox]
Make this cell an argument: =myFunction(A1)
Click checkbox to refresh the formula
Use a google finance function as a parameter. Like =GOOGLEFINANCE("CURRENCY:CADARS")
Those function force reload every x minutes
Since google app script is an extension of JS, functions should be able to handle more args than defined in function signature or fewer. So if you have some function like
function ADD(a, b) {
return CONSTANTS!$A$1 + a + b
}
then you'd call this func like
=ADD(A1, B1, $A$2)
where $A$2 is some checkbox (insert -> checkbox) that you can click to "refresh" after you needed to change the value from the sheet & cell CONSTANTS$A$1
I use a dummy variable in a function, this variable refers to a cell in the spreadsheet. Then I have a Myfunction() in script that writes a Math.Random number in that cell.
MyFunction is under a trigger service (Edit/Current Project Triggers) and you can choose different event-triggers, for example On-Open or time driven, there you can choose for example a time period, from 1 minute to a month.
Working off of Lexi's script as-is, it didn't seem to work anymore with the current Sheets, but if I add the dummy variable into my function as a parameter (no need to actually use it inside the function), it will indeed force google sheets to refresh the page again.
So, declaration like: function myFunction(firstParam,dummy) and then calling it would be as has been suggested. That worked for me.
Also, if it is a nuisance for a random variable to appear on all of your sheets that you edit, an easy remedy to limit to one sheet is as follows:
function onEdit(e)
{
e.source.getSheetByName('THESHEETNAME').getRange('J1').setValue(Math.random());
}
another solution to the caching problem.
have a dummy variable in your method.
pass
Filter(<the cell or cell range>,1=1)
as the value to that parameter.
e.g.
=getValueScript("B1","B4:Z10", filter(B4:Z10,1=1))
the output of filter is not used. however it indicates to the spreadsheet that this formula is sensitive to B4:Z10 range.
I had a similar issue creating a dashboard for work. Chamil's solution above (namely using Sheet's Filter function passed as the value to a dummy variable in your function) works just fine, despite the more recent comment from Arsen. In my case, I was using a function to monitor a range and could not use the filter on the same range since it created a circular reference. So I just had a cell (in my case E45 in the code below) in which I changed the number anytime I wanted my function to update:
=myFunction("E3:E43","D44",filter(E45,1=1))
As Chamil indicated, the filter is not used in the script:
function myFunction(range, colorRef, dummy) {
variable 'dummy' not used in code here
}
Today I solved this by
adding another parameter to my function:
function MY_FUNC(a, b, additional_param) { /* ... */ }
adding a value to this parameter as well, referencing a cell:
=MY_FUNC("a", "b", A1)
and putting a checkbox in that referenced cell (A1).
Now, it takes only one click (on the checkbox) to force recalculating my function.
What you could do is to set up another cell somewhere in the spreadsheet that will be updated every time a new sheet is added. Make sure it doesn't update for every change but only when you want to do the calculation (in your case when you add a sheet). You then pass the reference to this cell to your custom function. As mentioned the custom function can ignore this parameter.
Given that feature explained by Henrique Abreu, you may try the out-of-box spreadsheet function QUERY , that SQL liked query is what I use often in work
on raw data, and get data as summary to a different tab, result data is updated in real time following change in raw data.
My suggestion is based on the fact that your script has not advanced work such as URL fetch, just data work, as without actual data read, I cannot give a precise solution with QUERY.
Regarding the cache feature mentioned by Henrique Abreu (I don't have enough reputation to comment directly under his answer), I did testing and found that:
looks there is no cache working, testing function's script shown below:
function adder(base) {
Utilities.sleep(5000);
return base + 10;
}
applying that custom function adder() in sheet by calling a cell, and then changed that cell value forth and back, each time I see the loading message and total time more than 5 seconds.
It might be related to the update mentioned in this GAS issue:
This issue has now been fixed. Custom functions in New Sheets are now context aware and do not cache values as aggressively.
the issue mentioned in this topic remains, my testing suggests that, Google sheet recalculate custom function each time ONLY WHEN
value DIRECTLY called by function is changed.
function getCellValue(sheetName,row,col)
{
var ss= SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName(sheetName);
return sh.getRange(row, col).getValue();
}
A change of any value in yellow cells will lead to recalculation of custom function; the real data source value change is ignored by function.
function containing cell's location is changed in sheet. ex. insert/remove a row/column above or left side.
I did not want to have a dummy parameter. YMMV on this.
1 A cell that is a 'List of Items', one is "Refresh"
2 Script with 'onEdit', if the cell is "Refresh":
a)Empty out the document cache
b)Fill doc cache with external data (a table in my case)
c)For all cells with my 'getStockoData(...' custom function
get the formula
set '=0'
set the fromula
d)Set the cell in (1) with a value of "Ready"
This does refresh the bits you want BUT IS NOT FAST.
I followed this video, from 1:44, and this worked for me.
You should use a specific update function, initialize a "current time" variable and pass this permanently updated variable to your custom function. Then go to Triggers and set up an "every-minute" time-driven trigger for the update function (or choose another time interval for updates).
The code:
function update() {
var dt = new Date();
var ts = dt.toLocaleTimeString();
var cellVal = '=CustomFunction("'+ ts + '")';
SpreadsheetApp.getActiveSheet().getRange('A1').setValue(cellVal);
}
Just add GOOGLEFINANCE("eurusd") as an additional argument to your custom function, like:
=myFunction(arg1, arg2, GOOGLEFINANCE("eurusd"))
As #Brionius said put an extra dinamic argument on the function. if you use now() you may have timeout problems make the update a little bit slower...
cell A1 = int(now()*1000)
cell A2 = function(args..., A1)
If you have written a custom function and used it in your spreadsheet as a formula, then each time you open the spreadsheet or any referencing cell is modified, the formula is recalculated.
If you want to just keep staring at the spreadsheet and want its values to change, then consider adding a timed trigger that will update the cells. Read more about triggers here