1
votes

I am new to google and am trying to create spreadsheets and then move it to a specific folder.

On the "Synthése Mag" sheet I have all the name I gave to the files.

The spreadsheet are successfully created, however, when I try to move it, the following message appear :

Exception: Unexpected error while getting the method or property getFolderById on object DriveApp.

My code is the following :

  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Synthése mag'), true);
  for(var i=2;i<4;i++){
   var mag = spreadsheet.getSheetByName('Synthése mag').getRange(i,2).getValue ();
  
   var ssNew = SpreadsheetApp.create(mag);
Logger.log(ssNew.getUrl());
var newmag = DriveApp.getFilesByName(mag)
DriveApp.getFolderById("Folder ID").addFile(newmag)
  
};

}

Anyone could help ?

1

1 Answers

1
votes

Explanation:

  • The issue in the code is that getFilesByName does not return a File but a FileIterator. You want to get a file object and therefore you can use getFileById and pass the id of the file.

  • There is no need to activate a sheet and redefine the sheet inside the for loop.

  • Get all the values before the loop so you don't call getRange/getValue iteratively

Solution:

function myFunction() {
  const spreadsheet = SpreadsheetApp.getActive();
  const mag = spreadsheet.getSheetByName('Synthése mag');
  const names = mag.getRange('B2:B3').getValues().flat();
  names.forEach(nm=>{
    let ssNew = SpreadsheetApp.create(nm);
    let ssFile = DriveApp.getFileById(ssNew.getId());
    DriveApp.getFolderById("Folder ID").addFile(ssFile)
  })
};