How to copy a sheet to other spreadsheets and move

2019-03-05 15:53发布

I am using a script I found to copy the active sheet to all the other spreadsheets in a folder. It works fine, but I would actually like to have that copied sheet be set as the first (left-most) sheet in those other spreadsheets.

I know about "moveActiveSheet" but I can't seem to get it to work correctly (I'm still new to scripting.). The usage examples I have seen seem be for the current spreadsheet. Any help would be appreciated.

Current script:

function onOpen() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var pasteSheet = [ {name: "Paste Sheet", functionName: "copySheet"}];
  ss.addMenu("Copy to Spreadsheets", pasteSheet);
}

function copySheet() {
  var source = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = source.getSheets()[0];
  var sourceFile = DriveApp.getFileById(source.getId());
  var sourceFolder = sourceFile.getParents().next();
  var folderFiles = sourceFolder.getFiles();
  var thisFile; 

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

1条回答
We Are One
2楼-- · 2019-03-05 16:08

You just need to activate the sheet and then move it within currentSS after you set the name.

  currentSS.getSheets()[currentSS.getSheets().length-1].setName('THIS WAS COPIED').activate();
  currentSS.moveActiveSheet(1);
查看更多
登录 后发表回答