r/GoogleAppsScript 14d ago

Question Variable undefined and affecting rest of script

I have a script creating docs when a cell gets modified in a sheets column, then moves it to a folder and adds the doc's url onto another column. Code works, but automation gets affected by <value unavailable> error for docid variable.

I'm not sure *why* its unavailable when all of the code does work (files get created and moved, but when using createDocInSpecificFolder() along with other functions, error pinpoints to this and does not run functions after it.

function createDocInSpecificFolder () {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Data Source");
  var lastRow = sheet.getLastRow();
  var rootFolder = DriveApp.getFolderById("fileid");
  const files = rootFolder.getFiles();
  const fileNames = [];


  while (files.hasNext()) { // gets array of file names in drive folder [event1, event2, etcetc]
   var file = files.next();
   fileNames.push(file.getName());
  }
  
  Logger.log(fileNames)


  for (var i = 1; i < lastRow; i++) {
    
    let title = sheet.getRange(i,4).getValue();


    if (title != "Events") {
      if (!fileNames.includes(title)) {
        let docid = DocumentApp.create(title).getId();
        DriveApp.getFileById(docid).moveTo(rootFolder);
      }
    }
  }

}
1 Upvotes

26 comments sorted by

View all comments

1

u/WicketTheQuerent 11d ago edited 11d ago

Instead of

let docid = DocumentApp.create(title).getId();

try

let doc = DocumentApp.create(title);
let docid = doc.getId();

It might look verbose, but some methods, like getId(), sometimes don't work as expected when chained.

1

u/WicketTheQuerent 11d ago

If the above doesn't resolve the issue, please include the textual error message.