Modification points:
- In your script,
file
is FileIterator. - In your if statement,
file.next()
is used 2 times. In this case, 1stfile.next()
is different from 2ndfile.next()
. If the file of the filenamename.csv
are existing only one file, when 2ndfile.next()
is run, an error occurs. I thought that This might be the reason of your issue. - When you want to move the processed file to the trash box, it is required to use
setTrashed
for the 1stfile.next()
.
When above points are reflected to your script, it becomes as follows.
Modified script:
function importCSV () {
const folder = DriveApp.getFolderById("xyz");
const file = folder.getFilesByName("name.csv");
if (file.hasNext()) {
const f = file.next(); // Added
const csvString = f.getBlob().getDataAsString(); // Modified
const csvData = Utilities.parseCsv(csvString);
const lastRow = csvSheet.getLastRow();
csvSheet.getRange(lastRow+1,1,csvData.length,csvData[0].length).setValues(csvData);
f.setTrashed(true); // Modified
}
}
Reference:
CLICK HERE to find out more related problems solutions.