Skip to content

Instantly share code, notes, and snippets.

@katz
Last active April 15, 2021 14:58
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save katz/ab751588580469b35e08 to your computer and use it in GitHub Desktop.
Save katz/ab751588580469b35e08 to your computer and use it in GitHub Desktop.
Google Apps Script to re-calculate selected cells in Sheets
/**
* @OnlyCurrentDoc Limits the script to only accessing the current spreadsheet.
*/
/**
* Adds a custom menu with items to show the sidebar and dialog.
*
* @param {Object} e The event parameter for a simple onOpen trigger.
*/
function onOpen(e) {
SpreadsheetApp.getUi()
.createAddonMenu()
.addItem('Re-calculate selected cells', 'recalculate')
.addToUi();
}
/**
* Force Spreadsheet to re-calculate selected cells
*/
function recalculate(){
var activeRange = SpreadsheetApp.getActiveRange();
var originalFormulas = activeRange.getFormulas();
var originalValues = activeRange.getValues();
var valuesToEraseFormula = [];
var valuesToRestoreFormula = [];
originalFormulas.forEach(function(outerVal, outerIdx){
valuesToEraseFormula[outerIdx] = [];
valuesToRestoreFormula[outerIdx] = [];
outerVal.forEach(function(innerVal, innerIdx){
if('' === innerVal){
//The cell doesn't have formula
valuesToEraseFormula[outerIdx][innerIdx] = originalValues[outerIdx][innerIdx];
valuesToRestoreFormula[outerIdx][innerIdx] = originalValues[outerIdx][innerIdx];
}else{
//The cell has a formula.
valuesToEraseFormula[outerIdx][innerIdx] = '';
valuesToRestoreFormula[outerIdx][innerIdx] = originalFormulas[outerIdx][innerIdx];
}
})
})
activeRange.setValues(valuesToEraseFormula);
activeRange.setValues(valuesToRestoreFormula);
}
/**
* Runs when the add-on is installed; calls onOpen() to ensure menu creation and
* any other initializion work is done immediately.
*
* @param {Object} e The event parameter for a simple onInstall trigger.
*/
function onInstall(e) {
onOpen(e);
}
@mariusbutuc
Copy link

Is there an alternative to SpreadsheetApp.getActiveRange() that would do "SpreadsheetApp.getEverything()"? 😄

@nicoloalabastro
Copy link

@mariusbutuc givean a variable sheet of type Sheet you can do sheet.getDataRange().
This is functionally equivalent to creating a Range bounded by A1 and (Range.getLastColumn(), Range.getLastRow())

https://developers.google.com/apps-script/reference/spreadsheet/sheet#getdatarange

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment