0
votes

Today I can't run scripts connected to a specific Google Spreadsheet which contains .next() function calls, which I use to access other Spreadsheets by name. It shows Running script Cancel Dismiss message at the top of spreadsheet until exceeding maximum execution time. The strange thing is that I have similar files for every day with exactly same scripts, and the one for yesterday works fine. I created MWE below. So, when I run it I can get the alerts for the first 2 messages, but not the 3rd one.

function test_script_hanging() {
    var ui = SpreadsheetApp.getUi();
    ui.alert("before getting files by name");
    var getFilefile = DriveApp.getFilesByName("file");
    ui.alert("after getting files by name");
    var getID = getFilefile.next().getId();
    ui.alert("after getting Id");
}

In some situations I notice an error message saying something like "Authorization is needed to perform this action" on the line where the .next() function is being called. I tried to revoke authorization of the file and give authorization again, but that didn't help. I tried to give full access to a given script, but couldn't google the way to do it. Maybe I can add some more functions in my script to require full access during authorization, and maybe that will help to run my main function. My questions are:

  1. Why the script hangs?
  2. How to fix this?
  3. Can such kind of things (randomly and without any notice) happen in a free version of Google account?
1
Try Cooper's solution. The getFilesByName() method returns a FileIterator that you then call the next() method on. If the iterator has reached the end, calling next() will throw an exception and stop your script. You must check if iterator has reached the end by using hasNext() in a while loop - Anton Dementiev
The next day of this issue, everything started to work as earlier, without me changing anything. Probably it was some issue/bug on the Google's site. And I didn't have a chance to check any of the replies. @AntonDementiev thanks for you answer, I know what are you talking about, but I am sure my iterator didn't reach the and as I have the file with name "file" created in the drive, and it didn't throw any exception, it just hangs without any kind of error messages, regardless of where I ran a script from the sheets itself or from the script editor. - eRic

1 Answers

1
votes

This works for me:

  var fldr = DriveApp.getFolderById(folderID)
  var file = fldr.getFilesByName(filename);
  while(file.hasNext())
  {
    var fi = file.next();
    if(fi.getName() == filename)
    {
      var id=fi.getId();
    }
  }