I have a function that is supposed to only run when called by a menu click
. But it is being executed many many times, and even without even clicking on the menu item
on the sheet itself.
I originally had this function as a custom function to be executed on the target sheet as a formula in a cell (=extractFormulas(parm)
), but decided that it would be more efficient to call it only once (from a menu) and iterate through the rows in question, writing the results in the sheet using setValue(result)
. But somehow it seems as if the sheet has a memory and executes it as a cell custom function.
function onOpen() { //create menu item
var ui = SpreadsheetApp.getUi();
ui.createMenu('Reconcile_Bank')
.addItem('Get amounts from bank', 'extractFormulas')
.addToUi();
}
function extractFormulas() {
Logger.log('*********Starting extractFormulas()************');
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Jan");
const lrow = sheet.getLastRow();
const receiptsRange = sheet.getRange("C5:C" + lrow);
var budgetEntries = receiptsRange.getValues();
var budgetFormulas = receiptsRange.getFormulas();
var result = '';
var amount = 0;
var idx = '';
for (j=29; j<lrow; j++) {
result = '';
amount = sheet.getRange(j,12).getValue();
Logger.log('row: '+ j + ' amount: '+ amount);
if (amount = 0) continue;
if (amount > 0)
result = 'deposit';
else {
idx = budgetFormulas.findIndex(([c]) => [...c.matchAll(/b[.d]*/g)].some(([e]) => e == -amount.toString()));
if (idx > -1) {
result = receiptsRange.offset(idx, 0, 1, 1).getA1Notation()+"|"+receiptsRange.offset(idx, -1, 1, 1).getValue();
Logger.log('Formula found: '+result);
continue; //refers to outer loop for (j=29; j<lrow; j++) {
}
else //not in a formula
for (var i = 0; i<budgetEntries.length; i++) {
if (budgetEntries[i][0].toString() == -amount.toString()) {
result = 'C'+(i+5)+'|'+sheet.getRange(i+5,2).getValue();
Logger.log('non-Formula found '+ result + 'matched to '+budgetEntries[i][0].toString());
break; //refers to inner loop for (var i = 0; i<budgetEntries.length; i++) {
}
}
}
if (result == '')
result = 'not found';
sheet.getRange(j,9).setValue(result);
}
return;
}
6
As the execution logs show “Custom Function” in the Type column, your spreadsheet still has formulas, including extractFormulas
as a formula function.
Please remove this function from all the formulas, even those in hidden sheets.
You could use the UI Search function by checking Also search within formulas. Another option is to use Apps Script to find which formulas use this function.
It’s worth noting that your script has at least one syntax error: using =
(if (amount = 0) continue;
) instead of ==
or ===
.
1