For a project I am working on I created a trigger to run my makeCopy() function at the beginning of every year. The goal is to make a copy of a spreadsheet and save it in a folder already created in my drive. In this function I also create a new folder for the new year.
function makeCopy(){
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var d = new Date();
var year = d.getYear();
var FolderName = "Time Off Request - " + year;
DriveApp.createFolder(FolderName);
year = year - 1;
var FileName = "Copy of Time Off Request - " + year;
Logger.log(FolderName);
FolderName = "Time Off Request - " + year;
var FolderID = DriveApp.getFoldersByName(FolderName).next().getId();
Logger.log(FolderID);
var destFolder = DriveApp.getFolderById(FolderID);
Logger.log(destFolder);
DriveApp.getFileById(sheet.getId()).makeCopy(FileName, destFolder);
}
This code actually ran and worked the first time. However, every time I try to test it again I get the error, "Cannot retrieve the next object: iterator has reached the end. " On the line where I try to get my folder ID. How can I fix this error and get the folder ID of the folder in my drive so I can make a copy of the spreadsheet to that folder.
You get that specific error, Cannot retrieve the next object: iterator has reached the end.
, because the search for that folder name yielded an empty result set. If you alter your program structure to only use next()
if the iterator's hasNext()
method returns true, you will not get that error anymore. However, such a change will not make your search term suddenly find results. It does, however, allow for making repeated attempts with different search queries.
I suggest renaming your variables to be expressive of their intent:
// Copy the current file into last year's folder, and create this year's folder.
function makeCopy() {
var now = new Date();
var thisYear = now.getYear();
var lastYear = thisYear - 1;
var query = "Time Off Request - " + lastYear;
var folderIterator = DriveApp.getFoldersByName(query);
// Instead of throwing an error, you could modify this to be a while loop
// that requests a search term from the user - see Browser/UI and inputBox
// and updates folderIterator. If you do that, you'll want to add guards
// that ensure the correct folder will be the first result.
if (!folderIterator.hasNext()) {
throw new Error("Bad search term - no folders with name '" + query + "' exist!");
}
var lastYearFolder = folderIterator.next();
console.log({message: "Backup of Time Off Requests",
query: query,
destFolder: lastYearFolder.getName()}
); // View->Stackdriver Logging
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var backupName = "Copy of Time Off Request - " + lastYear;
DriveApp.getFileById(sheet.getId()).makeCopy(backupName, lastYearFolder);
// Before exiting, now that the backup is done, create this year's folder.
DriveApp.createFolder("Time Off Request - " + thisYear);
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加