Search code examples
javascriptgoogle-sheetsgoogle-apps-scriptgoogle-docs

Prompt in GAS: "TypeError: Cannot read properties of null (reading 'getBody')" on a Google Sheets


I'm new at GAS and I was following a tutorial on Youtube for knowing how it works on the diferent plataforms on Google Workspace. But, when I executed my code in a Google Sheets it prompted me this error:

TypeError: Cannot read properties of null (reading 'getBody')

function InsertarDatos() {
  var DocActual = DriveApp.getFileById("1kM-zglMjbckKnacmV5K21j1r3CjDmn70yrzsCcKrNdw");
  var fila = 2;
  var nombreCelda = "A" + fila;
  var hojaActual = SpreadsheetApp.getActive();
  var celdaActual = hojaActual.getRange(nombreCelda);

  while (!celdaActual.isBlank()) {
    var DocNuevo = DocActual.makeCopy("Nombre: " + hojaActual.getRange("A" + fila).getValue());
    var documento = DocumentApp.getActiveDocument();

    var fecha = new Date();
    var mes = fecha.getMonth() + 1;
    var dia = fecha.getDate();
    var ano = fecha.getFullYear();
    var fechaT = "Certificado emitido el día " + dia + "del mes " + mes + " de " + ano + ".";
    
    documento.getBody().replaceText("<<nombre>>", hojaActual.getRange("A" + fila).getValue());
    documento.getBody().replaceText("<<dni>>", hojaActual.getRange("B" + fila).getValue());
    documento.getBody().replaceText("<<curso>>", hojaActual.getRange("C" + fila).getValue());
    documento.getBody().replaceText("<<empresa>>", hojaActual.getRange("D" + fila).getValue());
    documento.getBody().replaceText("<<calific>>", hojaActual.getRange("E" + fila).getValue());
    documento.getBody().replaceText("<<fecha>>", fechaT);

    fila++;
    nombreCelda = "A" + fila;
    celdaActual = hojaActual.getRange(nombreCelda);
  }
}

I expected that it created several documents replacing the different items that I would put in a database in a Google Sheets.The expected document


Solution

  • DocumentApp.getActiveDocument() returns null because the Google Apps Script project is contained by a spreadsheet.

    You might replace this with DocumentApp.openById(document_id) or DocumentApp.openByUrl(document_url). You should replace document_id / document_url with a string holding the document id / URL, respectively, or a variable to which this string was assigned.

    Related