Last active
April 15, 2021 14:58
-
-
Save katz/ab751588580469b35e08 to your computer and use it in GitHub Desktop.
Google Apps Script to re-calculate selected cells in Sheets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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 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
Is there an alternative to
SpreadsheetApp.getActiveRange()
that would do "SpreadsheetApp.getEverything()
"? 😄