Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google apps script: how to persist data in spreadsheet between different function calls?

In a Google spreadsheet using the Script Editor, I do function calls, but I am not quite sure if the best way to store persistant data (data that I will continue to use) is to use global variables (using objects, arrays, strings), or there is a better way to store data.

I don't want to use cells which could be another way.

Another question, is it possible to create (pseudo) classes in this environment? Best way?

like image 542
netadictos Avatar asked Nov 07 '11 16:11

netadictos


People also ask

How do I trigger an email in Google Sheets when a cell value changes?

This opens in a new window. Go to the actions panel, select the email icon, then add your formula (example: B2<10%), and then add an email subject, the person who will get the email and click on save. Once that's done, your Factivate spreadsheet will automatically generate an email once B2 changes below 10%.

How do you trigger an onEdit in Google Sheets?

The onEdit(e) trigger runs automatically when a user changes the value of any cell in a spreadsheet.


1 Answers

Both ScriptProperties and ScriptDB are deprecated.

Instead, you should be using the new class PropertiesService which is split into three sections of narrowing scope:

  • Document - Gets a property store that all users can access within the current document, if the script is published as an add-on.
  • Script - Gets a property store that all users can access, but only within this script.
  • User - Gets a property store that only the current user can access, and only within this script.

Here's an example persisting a user property across calls:

var properties = PropertiesService.getScriptProperties();

function saveValue(lastDate) {
  properties.setProperty('lastCalled', lastDate);
}

function getValue() {
  return properties.getProperty('lastCalled');
}

The script execution environment is stateless, so you cannot access local variables from previous runs, but you can store getScriptProperties() in a local variable because it will be re-run for each return trip to the server so it can be called in either method.


If you need to store something on a more temporary basis, you can use the CacheService API

like image 151
KyleMit Avatar answered Sep 18 '22 10:09

KyleMit