Home > Back-end >  Copy a Google sheet to multiple spreadsheets in a folder using the Folder ID
Copy a Google sheet to multiple spreadsheets in a folder using the Folder ID

Time:01-27

I currently have a script that I'm using, which I based on a script that I found, to copy a Google sheet to all the other Spreadsheets that are in the same Google Drive folder. I'd like to modify this to copy the sheet to all the other Spreadsheets that are in a different folder using the folder ID. I've tried modifying the var folderFiles to use the DriveApp.getFolderByID to direct it to a specific folder but just keep getting errors. I'm more of a novice so any help or guidance would be greatly appreciated.

function copySheetVA() {
  var source = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = source.getActiveSheet();
  var sourceFile = DriveApp.getFileById(source.getId());
  var sourceFolder = sourceFile.getParents().next();
  var folderFiles = DriveApp.getFolderById('1zZDvtFzIvmD-7Z5f5Sbi4G3-XXXXX');
  var thisFile; 

  while (folderFiles.hasNext()) {
    thisFile = folderFiles.next();
    if (thisFile.getName() !== sourceFile.getName()){
      var currentSS = SpreadsheetApp.openById(thisFile.getId());
      var actualSheetName = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
      sheet.copyTo(currentSS);
      currentSS.getSheets()[currentSS.getSheets().length-1].setName(actualSheetName);
    }    
  };    
}

CodePudding user response:

I updated your code and tested it on my end.

The fix is to call getFiles() after get the folder,

var folderFiles = DriveApp.getFolderById('YOUR_FOLDER_ID').getFiles();

function copySheetVA() {
  var source = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = source.getActiveSheet();
  var sourceFile = DriveApp.getFileById(source.getId());
  
  var folderFiles = DriveApp.getFolderById('YOUR_FOLDER_ID').getFiles();

  while (folderFiles.hasNext()) {
    var thisFile = folderFiles.next();
    if (thisFile.getName() !== sourceFile.getName()){
      var currentSS = SpreadsheetApp.openById(thisFile.getId());
      var actualSheetName = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
      sheet.copyTo(currentSS);
      currentSS.getSheets()[currentSS.getSheets().length-1].setName(actualSheetName);
    }    
  };    
}
  • Related