Search code examples
google-apps-scriptgoogle-drive-api

Create a google spreadsheet in same folder as current file


I have a google form script that I want to create a spreadsheet in the same folder as the form.

  var thisFileId = form.getId();
  var parentFolder = DriveApp.getFolderById(thisFileId)
  
  spreadsheet = SpreadsheetApp.create(spreadsheetName);
  var spreadsheetID = spreadsheet.getId();
  var spreasheetFile = DriveApp.getFileById(spreadsheetID);
  spreasheetFile.moveTo(parentFolder);

I get an error on the last line :

"Exception: Invalid argument: parent.mimeType"


Solution

  • I believe your goal as follows.

    • You want to create new Spreadsheet to the same folder with form.getId().

    Modification points:

    • In your script, about the variable name form of form.getId(), if form is the Google Form, form.getId() is the file ID of Google form. I think that this might be the reason of your issue.
    • In order to put the new Spreadsheet to the same folder with form, it is required to retrieve the parent folder of form.

    When above points are reflected to your script, it becomes as follows.

    Modified script:

    From:

    var parentFolder = DriveApp.getFolderById(thisFileId)
    

    To:

    var parentFolder = DriveApp.getFileById(thisFileId).getParents().next();
    

    Note:

    • It seems that when ID except for the folder ID is used for DriveApp.getFolderById(id), no error occurs.

    Reference: