0

I have two Global Variables catDeb and catCred
The values are defined in a func loadCategories and should be, I think, accessible every where. But its not updated out of funcs.

var catDeb  ;  // line 26 of code  
var catCred ;  // line 27 of code

they are initialized on the opening the spreadsheet onOpen(a)
It's seems to be ok.

the program begins here:

function onOpen(e) {  // line 40 of code
  loadCategories(wsCredit);  
  loadCategories(wsDebit);  
}  

function loadCategories(ws){  
  if (ws === wsCredit) {  
      var col   = 1 ; // Credit  
      var lines = par.getRange(2,col,par.getLastRow(), 4).getValues();  
      catCred   = lines.filter(function(r){return r[0].length>0});  
  } else {  
    col    = 10 ; // Debit  
    lines  = par.getRange(2,col,par.getLastRow(), 4).getValues();  
    catDeb = lines.filter(function(r){return r[0].length>0});  
  }  
}  

But when tried to acess the global variables catDeb or catCred it doesn't

function onEdit(e) {  
  var chosenCell = e.range;  
  
  var value = chosenCell.getValue();  
  var r     = chosenCell.getRow();  
  var c     = chosenCell.getColumn();  
  var p     = chosenCell.getSheet().getName();  
    
  if (p === wsDebit && r > 1) {  
    // altered Debit  
    if (c === coLevel1 ){  
        applyLevel1(value, r, deb);  
    } // shorter version
  }
}
function applyLevel1(value, r, db){  
  db.getRange(r , coLevel2).clearContent();  
  db.getRange(r , coLevel2).clearDataValidations();  
  db.getRange(r , coLevel3).clearContent();  
  db.getRange(r , coLevel3).clearDataValidations();  

    console.log("level 1 ="+db.getName());
    console.log(catCred);

  if (value != ""){
    if (db.getName() == 'Crédit'){
       var level   = catCred.filter(function (o) {return o[0] === value});
    } else {
       var level   = catDeb.filter(function (o) {return o[0] === value});
    };
    console.log(level);
    var options = level.map(function (o) {return o[1]});
    var cell    = db.getRange(r , coLevel2);

    applyValidation(options, cell);
  }
  leaveBlank(r, db);
}

If I use de Débit sheet, get an error:

2 lug 2021, 20:11:26 Errore ReferenceError: catDeb is not defined at unknown function

if I go the Crédit sheet the error catCred

What am I doing wrong.

TIA (aka Thanks in advance)

1 Answers1

0

In Google Apps Script global variables doesn't persist between executions. Instead use other mean to store those values. Some options among many others are to use the spreadsheet, the Properties and the Cache services.

Rubén
  • 34,714
  • 9
  • 70
  • 166