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

How to check if the cell is empty, if so skip it


I want to add 1 more line to check if the particular row is empty. If empty I want it to return.

    if (index === 0) return; // this to check header
    if (row[52]) return; // this to check if the row have data. if have it returns.

The full code for this part is below.

function createNewGoogleDocs() {
  //This value should be the id of your document template that we created in the last step
  const googleDocTemplate = DriveApp.getFileById('Google Doc');
  
  //This value should be the id of the folder where you want your completed documents stored
  const destinationFolder = DriveApp.getFolderById('Folder');
  //Here we store the sheet as a variable
  const sheet = SpreadsheetApp
    .getActiveSpreadsheet()
    .getSheetByName('List');
  
  //Now we get all of the values as a 2D array
  const rows = sheet.getDataRange().getValues();
  
  //Start processing each spreadsheet row
  rows.forEach(function(row, index){
    //Here we check if this row is the headers, if so we skip it
    if (index === 0) return;
    //Here we check if a document has already been generated by looking at 'Document Link', if so we skip it
    if (row[52]) return;
    //Using the row data in a template literal, we make a copy of our template document in our destinationFolder
    const copy = googleDocTemplate.makeCopy(`${row[4]} List` , destinationFolder)
    //Once we have the copy, we then open it using the DocumentApp
    const doc = DocumentApp.openById(copy.getId())
    //All of the content lives in the body, so we get that for editing
    const body = doc.getBody();

Solution

  • SpreadsheetApp.Range.getValues() returns an empty string from blank cells, considering this, you might use the following expression:

    row[52] === ''
    

    === is used to compare value and data type. Using == will work too, it only compare value, it relies on JavaScript data type conversion rules. If you aren't familiar with these rules, use ===.

    Using just !row[52] as a conditional expression is tricky because when row[52] is equal to '' or equal 0 and when it's undefined this expression returns true.

    Related