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

How to I move the current file to a folder?


I want to move the current file to a folder and remove it from the one that it is in, based on a cell value change. Here is what I have:

 function onEdit() {

var File = SpreadsheetApp.getActiveSpreadsheet();
var TransferComplete = File.getSheetByName("Sheet9").getRange("E24").getValue();

var ActiveFolder = DriveApp.getFolderById("a0lweiurnawoeiuranwv");
var ArchiveFolder = DriveApp.getFolderById("apsleriuoavwnoeiura");  



  if (TransferComplete = "Yes" ) 
  {ArchiveFolder.addFile(File) && ActiveFolder.removeFile(File)};


}

The error says that it cant find "add file" method.


Solution

  • To move a file, you must first get the file itself as a file and not as a spreadsheet.

    You need to use DriveApp.getFileById() to retrieve a file object that you can then pass into ArchiveFolder.addFile().

    Additionally you have some syntax errors with your code.

    • You are using an assignment operator = instead of a comparative operator == or '===' to compare TransferComplete to "Yes"
    • You don't need a statement seperator ; at the end of an if statement
    • You are using && to separate two statements, you need to separate them like so

      if(TransferComplete == "Yes" ){ ArchiveFolder.addFile(File); ActiveFolder.removeFile(File); }

    Corrected code:

    function onEdit() {
      var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
      var file = DriveApp.getFileById(spreadsheet.getId());
      var transfeComplete = spreadsheet.getSheetByName("Sheet9").getRange("E24").getValue();
    
      var activeFolder = DriveApp.getFolderById("a0lweiurnawoeiuranwv");
      var archivefolder = DriveApp.getFolderById("apsleriuoavwnoeiura");  
    
      if (transfeComplete === "Yes" ){
        archivefolder.addFile(file);
        activeFolder.removeFile(file);
      }
    }