Force IMPORTRANGE to update at certain intervals - google-sheets

I saw several complains about the delay of updating data through IMPORTRANGE in Google Sheets but I need the opposite and don't want the second sheet to get updated automatically, just update at the end of the day for example.
The code is already like this:
=IMPORTRANGE("The Key","The_Page!B:D")

I hacked around this by, on both spreadsheets by creating a refresh loop using a NOW cell, with both spreadsheets crossreferencing each other's NOW cell.
When the original sheet gets appended with a form submission or something, it updates its own NOW cell, and reupdates own IMPORTRANGE cell. The second spreadsheet follows suit, updating its own NOW cell to provide the original sheet with the correct data. Because the second spreadsheet has updated itself, it also updates the main IMPORTRANGE which refreshes the data you want it to display in the first place, as well as the IMPORTRANGE cell which gets the NOW cell from the original spreadsheet
At least, I'm pretty sure that's how it works. All I know, and all I care about, frankly, is that it works

Maybe you need to use the script editor and write a simple function of the kind:
function importData()
{
var ss = SpreadsheetApp.getActiveSpreadsheet(); //source ss
var sheet = ss.getSheetByName("The_Page"); //opens the sheet with your source data
var values = sheet.getRange("B:D").getValues(); //gets needed values
var ts = SpreadsheetApp.openById("The Key"); //target ss - paste your key
ts.getSheetByName("Name of the target sheet").getRange("B:D").setValues(values);
}
And then add a time-driven trigger to this project (Resources > Current project's triggers > Add a new one).

Related

How do I use ARRAYFORMULA and IF to apply a script to an entire column in Google Sheets?

I have little to no coding knowledge, so apologies if the solution is too obvious!
I am trying to add a Last Modified column to a Google Sheets file. To do this, I am using an AppScript function with the following code:
function setTimestamp(x) {
if(x != ""){
return new Date();
}
}
This works fine when I use setTimestamp(x) in my file. However, I am combining this with a Zapier action that creates a new row whenever new media is added. Every time a new row is created, any existing formulas are removed.
I assume I need to use ARRAYFORMULA to apply the setTimestamp formula to newly-created rows, but it must only apply to rows that aren't blank.
I have tried the following:
={"Last Modified";ARRAYFORMULA(setTimestamp(A2:A))} -> Only worked on first row
={"Last Modified";ARRAYFORMULA(B2:B=setTimestamp(A2:A))} -> Broke the file
={"Last Modified";ARRAYFORMULA(IF(A2:A)=1,setTimestamp(A2:A),"")} -> Expected 1 argument, got 3
Is there a way I can combine the IF into the script or a better way to solve the problem?
A public version of my file is available here: https://docs.google.com/spreadsheets/d/13zkVRPr2Wh5bHjCT8cenInHnBk7qkMkuEMdwUxC_cRU/edit?usp=sharing
All data is dummy data and stock photos.
Unfortunately, arrayformula does not function as an array map function for custom functions. (Even for native functions where you may expect it to work that way, it does not always, sadly.)
To handle array range, we need the custom function to handle array range directly. That also limits the number of individual calls to custom functions, which materially saves execution time.
To handle array range, there are 2 ways. I'll comment on both.
Array range directly as input of custom function
If the input is a single cell, it is read directly
If the input range spans more than a single cell, the data is read as nested lists: a list of lists of rows.
For example, A1 will be read as the data in A1. A1:B2 will be read as [[A1, B1], [A2, B2]].
You can remember it as columns of rows.
As for the input data format, numbers are taken without the display format. Texts are taken as strings.
If output is an array range, the result will automatically expend.
Thus, in your example, in B2 you can almost do
=setTimestamp(A2:A)
where setTimestamp() has been modified to
function out = setTimestamp(arr) {
out=Array(mat.length);
for (i=0;i<mat.length;i++){
j=0
if(arr[i][j] != ""){
out[i]=new Date();
}
}
return out
}
For more details, see the official help page. (Over the years, more details have become available.)
Almost, but not quite. For your direct question, above provides the answer. However, you seem to have an implicit requirement that your custom function is executed every time a new URL is found. Be careful that what happens here is that every time Google Sheet updates cell content, a new Date() is created and outputted.
Array range read within custom function
Since you know your URLs are in A2:A, and you want the output of your custom function to be B2:B, you can read and modify those ranges directly within your custom function via the Range Class.
In this route, you may find getLastRow(), getLastColumn() in Sheet and getNextDataCell() in Range convenient.
When you need to execute your custom function, you can run it manually or add onEdit() trigger to your custom function. (But onEdit() itself can mean substantial UI lag when using the sheet. It's usually more appropriate for sheets that parse external data automatically. See other triggers in the link for motions.)
In your example, you can almost do
function setTimestamp() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var lastRow = sheet.getLastRow();
var row=1;
var cell = sheet.getRange(row,1).getValue();
while (row<=lastRow) {
if(cell.getValue() != ""){
sheet.getRange(row,2).setValue(new Date());
}
cell = sheet.getRange(row,1,lastRow).getNextDataCell(SpreadsheetApp.Direction.DOWN);
row=cell.getRow();
}
}
which will scan for all URLs in A2:A and write current time to B2:B when executed.
Again, your example implicitly points to updating only when a new URL is found. So be careful about that. Use triggers as needed.
As for the need to place formula in B1, you can (and should) reference the output of your other application in a different sheet so that you or a different application of yours can edit without conflict.
Thus, for what was asked, we have everything.

How to use a value to search a tab and get a value from the new sheet in googlesheet

Hello i'm using google sheet as my second databse and in the main page called Companies i have a list of companies as shown below:
and i wrote a function that generate a new tab for every companie in the first column. here is what a tab looks like
my goal is in the companies tab under "Workers" i want to get the value of "Total workers" of each companie. the list of companies will be constantly growing so i thought about maybe a function that uses the value of the first column to search for the tab and then get the value of G2.
I am really new to google sheet and i would appreciate any help on how to solve this problem
SUGGESTION
You can try this sample script below with custom function named getTotalWorkers & then add it as a bound script to your Spreadsheet file:
UPDATED Script:
function getTotalWorkers(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var names = ss.getRange("Company!A2:A").getValues().filter(String); //get names of the sheets on column A
var res = [];
for(x=0; x<names.length; x++){
var data = ss.getRange(names[x]+"!G2").getValue(); //get the current cell G2 values on every sheet tabs
res.push([data]); //place all values to a tem[orayr array variable
}
ss.getSheetByName("Company").getRange(2,6,res.length,1).setValues(res); //add the values under the "Workers" column on Company sheet tab
}
Sample Demonstration
After saving the script from the Apps Script editor, place the updated getTotalWorkers function to a time-driven trigger:
The time driven trigger will auto populate the "Workers" F column cells every minute (based on my sample time-driven trigger configuration):

To make endless row on google spreadsheet

Very simple question.
How do you make endless row on spreadsheet? Like Excel.
I have this problem when I use google sheet to scan barcodes.
When rows reached 1000, I need to add more manually.
But sometimes I forget, then I keep scanning.
After that I check my sheet, I missed a lot of input but I don't remember which barcode was the last one, so I have to do them all over again after increasing the rows.
If google sheets has the infinite rows like Excel, I won't have to worry about it no more.
Do you guys have any solutions on this?
Use Apps Script to Make Your Sheet Dynamic
With Apps Script, you can write a function to detect how many cells are between the data inserted and the end of the spreadsheet, and add rows if they are too close.
function addRowsIfCloseToEnd() {
let file = SpreadsheetApp.getActive();
// INPUT YOUR SHEET NAME HERE
let sheet = file.getSheetByName("Sheet1");
let maxRow = sheet.getMaxRows()
let lastRow = sheet.getLastRow()
// In this example, when the values are 100 rows
// from the end of the sheet, it will add 100 rows
// to the end. Change this to your liking.
if (maxRow - lastRow < 100) {
sheet.insertRowsAfter(maxRow, 100)
}
}
In this example, the function checks when values are less than 100 rows from the end of the spreadsheet, and if it is, it will add 100 extra rows to the sheet.
You should adjust these numbers to suit your workflow, I don't know how many bar codes you scan or how quickly.
You have two options for how to trigger this:
onEdit
This is a simple trigger designed to run a function every single time there is an edit on the sheet. You can call the previous function like this:
function onEdit() {
addRowsIfCloseToEnd()
}
If you have authorized your script, then this should run every time you make an edit:
In this example I only add 10 rows every time, to demonstrate.
Time-based trigger
Depending on how many barcodes you scan and how quickly, you may not want this function to run every single time you scan a barcode, in which case you can make a trigger to run every 5 minutes for example:
function createClockTrigger() {
ScriptApp.newTrigger("addRowsIfCloseToEnd")
.timeBased()
.everyMinutes(5)
.create();
}
References
Apps Script
Tutorials
Simple Triggers
onEdit
ClockTriggerBuilder

googlesheets gives old or cached data when downloading with curl

I'm using this url to download a googlesheet programmatically https://docs.google.com/spreadsheets/d/{SHEET_ID}/export?gid=0&format=csv
For some reason every once in a while it gives old data, like 1 week old or something. This is completely random. Sometimes it even shows fresh data, and goes back to old data the next request.
The sheet in question is public but importing data from a private sheet like this
=QUERY(IMPORTRANGE("https://docs.google.com/spreadsheets/d/SHEET_ID", "sheet!A:Z"), "SELECT * WHERE Col1 LIKE '%keyword%'", 1)
The private sheet is also importing data from another sheet. Anything I can do to prevent this seemingly non-deterministic bug?
Similar behaviour observed with a published sheet which is designed to show time and a live schedule. "Recalculate every minute" setting didn't help. Solution is to put some value into a cell with a script. The script is set to run every minute.
function Somechanges() {
var someValue = Math.random();
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getRange('J1').activate();
spreadsheet.getCurrentCell().setValue(someValue);
};

Is there a Google Sheets formula to put the name of the sheet into a cell?

The following illustration should help:
Here is what I found for Google Sheets:
To get the current sheet name in Google sheets, the following simple script can help you without entering the name manually, please do as this:
Click Tools > Script editor
In the opened project window, copy and paste the below script code into the blank Code window, see screenshot:
......................
function sheetName() {
return SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
}
Then save the code window, and go back to the sheet that you want to get its name, then enter this formula: =sheetName() in a cell, and press Enter key, the sheet name will be displayed at once.
See this link with added screenshots: https://www.extendoffice.com/documents/excel/5222-google-sheets-get-list-of-sheets.html
You have 2 options, and I am not sure if I am a fan of either of them, but that is my opinion. You may feel differently:
Option 1: Force the function to run.
A function in a cell does not run unless it references a cell that has changed. Changing a sheet name does not trigger any functions in the spreadsheet. But we can force the function to run by passing a range to it and whenever an item in that range changes, the function will trigger.
You can use the below script to create a custom function which will retrieve the name:
function mySheetName() {
var key = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
return key;
}
and in the cell place the following:
=mySheetName(A1:Z)
Now if any value in a cell in that passed range changes the script will run. This takes a second to run the script and sets a message in the cell each time any value is changed so this could become annoying very quickly. As already mentioned, it also requires a change in the range to cause it to trigger, so not really helpful on a fairly static file.
Option 2: Use the OnChange Event
While the run time feels better than the above option, and this does not depend on a value changing in the spreadsheet's cells, I do not like this because it forces where the name goes. You could use a Utilities sheet to define this location in various sheets if you wish. Below is the basic idea and may get you started if you like this option.
The OnChange event is triggered when the sheet name is changed. You can make the code below more sophisticated to check for errors, check the sheet ID to only work on a given sheet, etc. The basic code, however, is:
function setSheetName(e) {
var key = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange('K1').setValue(key);
}
Once you have saved the code, in the script editor set the Current Project's On Change Trigger to this function. It will write the sheet name to cell K1 on any change event. To set the trigger, select Current project's triggers under the Edit menu.
If you reference the sheet from another sheet, you can get the sheet name using the CELL function. You can then use regex to extract out the sheet name.
=REGEXREPLACE(CELL("address",'SHEET NAME'!A1),"'?([^']+)'?!.*","$1")
update:
The formula will automatically update 'SHEET NAME' with future changes, but you will need to reference a cell (such as A1) on that sheet when the formula is originally entered.
Not using script:
I think I've found a stupid workaround using =cell() and a helper sheet. Thus avoiding custom functions and apps script.
=cell("address",[reference]) will provide you with a string reference (i.e. "$A$1") to the address of the cell referred to. Problem is it will not provide the sheet reference unless the cell is in a different sheet!
So:
where
This also works for named sheets. Then by all means adjust to work for your use case.
Source: https://docs.google.com/spreadsheets/d/1_iTD6if3Br6nV5Bn5vd0E0xRCKcXhJLZOQqkuSWvDtE/edit#gid=1898848593
EDIT:
I've added another workaround in the document that makes use of =formulatext() and some traditional text functions. By referencing to a cell in the current sheet using it's full address, i.e. Sheet1A1 you are able to use formulatext() to extract only the sheet name.
Here is my proposal for a script which returns the name of the sheet from its position in the sheet list in parameter. If no parameter is provided, the current sheet name is returned.
function sheetName(idx) {
if (!idx)
return SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
else {
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
var idx = parseInt(idx);
if (isNaN(idx) || idx < 1 || sheets.length < idx)
throw "Invalid parameter (it should be a number from 0 to "+sheets.length+")";
return sheets[idx-1].getName();
}
}
You can then use it in a cell like any function
=sheetName() // display current sheet name
=sheetName(1) // display first sheet name
=sheetName(5) // display 5th sheet name
As described by other answers, you need to add this code in a script with :
Tools > Script editor
An old thread, but a useful one... so here's some additional code.
First, in response to Craig's point about the regex being overly greedy and failing for sheet names containing a single quote, this should do the trick (replace 'SHEETNAME'!A1 with your own sheet & cell reference):
=IF(TODAY()=TODAY(), SUBSTITUTE(REGEXREPLACE(CELL("address",'SHEETNAME'!A1),"'?(.+?)'?!\$.*","$1"),"''","'", ""), "")
It uses a lazy match (the ".+?") to find a character string (squotes included) that may or may not be enclosed by squotes but is definitely terminated by bang dollar ("!$") followed by any number of characters. Google Sheets actually protects squotes within a sheet name by appending another squote (as in ''), so the SUBSTITUTE is needed to reduce these back to single squotes.
The formula also allows for sheet names that contain bangs ("!"), but will fail for names using bang dollars ("!$") - if you really need to make your sheet names to look like full absolute cell references then put a separating character between the bang and the dollar (such as a space).
Note that it will only work correctly when pointed at a different sheet from the one that the formula resides! This is because CELL("address" returns just the cell reference (not the sheet name) when used on the same sheet. If you need a sheet to show its own name then put the formula in a cell on another sheet, point it at your target sheet, and then reference the formula cell from the target sheet. I often have a "Meta" sheet in my workbooks to hold settings, common values, database matching criteria, etc so that's also where I put this formula.
As others have said many times above, Google Sheets will only notice changes to the sheet name if you set the workbook's recalculation to "On change and every minute" which you can find on the File|Settings|Calculation menu. It can take up to a whole minute for the change to be picked up.
Secondly, if like me you happen to need an inter-operable formula that works on both Google Sheets and Excel (which for older versions at least doesn't have the REGEXREPLACE function), try:
=IF(IFERROR(INFO("release"), 0)=0, IF(TODAY()=TODAY(), SUBSTITUTE(REGEXREPLACE(CELL("address",'SHEETNAME'!A1),"'?(.+?)'?!\$.*","$1"),"''","'", ""), ""), MID(CELL("filename",'SHEETNAME'!A1),FIND("]",CELL("filename",'SHEETNAME'!A1))+1,255))
This uses INFO("release") to determine which platform we are on... Excel returns a number >0 whereas Google Sheets does not implement the INFO function and generates an error which the formula traps into a 0 and uses for numerical comparison. The Google code branch is as above.
For clarity and completeness, this is the Excel-only version (which does correctly return the name of the sheet it resides on):
=MID(CELL("filename",'SHEETNAME'!A1),FIND("]",CELL("filename",'SHEETNAME'!A1))+1,255)
It looks for the "]" filename terminator in the output of CELL("filename" and extracts the sheet name from the remaining part of the string using the MID function. Excel doesn't allow sheet names to contain "]" so this works for all possible sheet names. In the inter-operable version, Excel is happy to be fed a call to the non-existent REGEXREPLACE function because it never gets to execute the Google code branch.
I have a sheet that is made to used by others and I have quite a few indirect() references around, so I need to formulaically handle a changed sheet tab name.
I used the formula from JohnP2 (below) but was having trouble because it didn't update automatically when a sheet name was changed. You need to go to the actual formula, make an arbitrary change and refresh to run it again.
=REGEXREPLACE(CELL("address",'SHEET NAME'!A1),"'?([^']+)'?!.*","$1")
I solved this by using info found in this solution on how to force a function to refresh. It may not be the most elegant solution, but it forced Sheets to pay attention to this cell and update it regularly, so that it catches an updated sheet title.
=IF(TODAY()=TODAY(), REGEXREPLACE(CELL("address",'SHEET NAME'!A1),"'?([^']+)'?!.*","$1"), "")
Using this, Sheets know to refresh this cell every time you make a change, which results in the address being updated whenever it gets renamed by a user.
I got this to finally work in a semi-automatic fashion without the use of scripts... but it does take up 3 cells to pull it off. Borrowing from a bit from previous answers, I start with a cell that has nothing more than =NOW() it in to show the time. For example, we'll put this into cell A1...
=NOW()
This function updates automatically every minute. In the next cell, put a pointer formula using the sheets own name to point to the previous cell. For example, we'll put this in A2...
='Sheet Name'!A1
Cell formatting aside, cell A1 and A2 should at this point display the same content... namely the current time.
And, the last cell is the part I'm borrowing from previous solutions using a regex expression to pull the fomula from the second cell and then strip out the name of the sheet from said formula. For example, we'll put this into cell A3...
=REGEXREPLACE(FORMULATEXT(A2),"='?([^']+)'?!.*","$1")
At this point, the resultant value displayed in A3 should be the name of the sheet.
From my experience, as soon as the name of the sheet is changed, the formula in A2 is immediately updated. However that's not enough to trigger A3 to update. But, every minute when cell A1 recalculates the time, the result of the formula in cell A2 is subsequently updated and then that in turn triggers A3 to update with the new sheet name. It's not a compact solution... but it does seem to work.
To match rare sheets names like:
Wow!
Oh'Really!
''!
use the formula:
=SUBSTITUTE(REGEXEXTRACT(CELL("address";Sheet500!A1);"'?((?U).*)'?!\$[A-Za-z]+\$\d+$");"''";"'")
or
=IF(NOW();SUBSTITUTE(REGEXEXTRACT(FORMULATEXT(A1);"='?((?U).*)'?![A-Za-z]+\d+$");"''";"'")) if A1 is formula reference to your sheet.
if you want to use build-in functions:
=REGEXEXTRACT(cell("address";'Sheet1'!A1);"^'(.*)'!\$A\$1$")
Explanation:
cell("address";'Sheet1'!A1) gives you the address of the sheet, output is 'Sheet1'!$A$1. Now we need to extract the actual sheet name from this output. I'm using REGEXEXTRACT to match it by regex ^'(.*)'!\$A\$1$, but you can either use more/less specific regex or use functions like SUBSTITUTE or REPLACE

Resources