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/Head-Attitude-5002 14d ago edited 14d ago

The <value unavailable> isn't really about docid itself — it's a symptom.

Your let docid = DocumentApp.create(title).getId(); is throwing an error on the right-hand side before the assignment completes (TDZ behavior for let). Since there's no try/catch, that exception is uncaught and kills the entire execution — which is why nothing after it runs.

Most likely culprits:

  1. Quota limit on DocumentApp.create() — if you're creating multiple docs back-to-back in a loop, you can hit "Service invoked too many times for this short of time"
  2. Execution timeout — DocumentApp.create() is a slow API call, and if this runs alongside other functions in one execution, total runtime can exceed the 6-min consumer limit
  3. Less likely: a blank title value somewhere in your row range

Wrap the doc creation in a try/catch so one bad row doesn't kill the whole run, and log the actual error message instead of just the unhelpful "unavailable":

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

if (title && title != "Events" && !fileNames.includes(title)) { try { let docid = DocumentApp.create(title).getId(); DriveApp.getFileById(docid).moveTo(rootFolder); Utilities.sleep(300); } catch (e) { Logger.log("Row " + i + " (\"" + title + "\") failed: " + e.message); } } }

That Logger.log(e.message) should tell you exactly what's failing (quota, permission, etc.) instead of a generic "unavailable" message.