0

I have a simple script like this

function importazione() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const wsd = ss.getSheetByName("morosi");
  wsd.getRange(2,1,1000,10).clearContent();
  SpreadsheetApp.flush();

  const ws = ss.getSheetByName("importa");
  const max_riga = ws.getLastRow();
  var dati = ws.getRange(2, 1, max_riga-1, 6).getValues();
  
  dati.forEach(r => {                  
    scriviElenco({
      corso: r[0],
      ciclo: r[1],
      studente: r[2],
      status: r[4],
      id_matr: r[5]
    });
  });
}

function scriviElenco(passa) {
  if (passa.status === "NO PAGÓ") {    
    var daSplittare = passa.corso+"|"+passa.studente+"|"+passa.id_matr;
    var riga = [];
    riga = daSplittare.split("|");
    wsd.appendRow(riga);
  };
}

it returns this error on the last line:

ReferenceError: wsd is not defined

I don't understand why wsd constant is not defined, I have much more complex scripts in which I use the same definitions and it works. Could someone help me to understand please?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38

1 Answers1

0

I don't understand why wsd constant is not defined

wsd is not in scope within your second function, scriviElenco(); it is only in scope within importazione() - since Javascript const definitions have block scope. And this actually makes sense, because wsd is only set when you execute importazione(), and you can't expect it to have a valid value in the second function. So, you'll probably have to write something like:

function scriviElenco(passa) {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const wsd = ss.getSheetByName("morosi");
  // your existing implementation
}

and perhaps even a one-liner helper function such as:

function getSheet(sheetName) {
  return SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
}

which you assign to a constant at the beginning of each of the two functions.

einpoklum
  • 118,144
  • 57
  • 340
  • 684