copyTo(destination,copyPasteType,transposed)停止执行其余功能

时间:2018-06-26 22:58:06

标签: google-apps-script google-sheets

我正在尝试使用函数copyTo(destination, copyPasteType, transposed)将一个文件中的工作表复制到另一个文件中的另一工作表,同时保持所有内容(包括列宽)相同。仅使用函数copyTo(destination),我的代码就可以工作,而且我想要的所有内容都保存在不同的文件中,除了列宽。但是,当我尝试将copyTocopyPasteType参数一起使用时,工作表将被完美地复制(具有正确的列宽),但是任何后续代码都不会运行。为什么会发生这种情况,我该如何解决?

function createSpreadsheet(foldername) {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = spreadsheet.getSheetByName('Sheet1');

  var folder = DriveApp.getFolderById(foldername);

  RESPONSE = FileName(); //a function that prompts the user for a filename

  //creates a new spreadsheet which has two sheets, and deletes the "Copy of Sheet1" sheet
  var newSpreadsheet = SpreadsheetApp.create(RESPONSE);
  var newsheet = newSpreadsheet.getSheetByName('Sheet1');
  var copysheet = sheet.copyTo(newSpreadsheet);
  sheet.copyTo(newSpreadsheet, SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);

  //when using CopyPasteType argument, everything from here down isn't run
  copysheet.getDataRange().copyTo(newsheet.getDataRange());
  copysheet.getDataRange().copyTo(newsheet.getDataRange(), 
  SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
  newSpreadsheet.deleteSheet(copysheet);

  var newSpreadsheetID = newSpreadsheet.getId();
  var file = DriveApp.getFileById(newSpreadsheetID);
  folder.addFile(file); 
  DriveApp.removeFile(file);
  clearYellow(); //clears contents of yellow cells
  clearGray(); //clears contents of gray cells
}

我也asked this question in Google+

1 个答案:

答案 0 :(得分:0)

我没有找到关于为什么带有三个参数的copyTo阻止我的函数其余部分执行的答案,但是我找到了另一种将列宽复制到新的电子表格中的方法。

function createSpreadsheet(foldername) {
  var oldspreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var oldsheet = oldspreadsheet.getSheetByName('Sheet1');

  var folder = DriveApp.getFolderById(foldername);

  RESPONSE = FileName();

  //creates a new spreadsheet which has two sheets, and deletes the "Copy of Sheet1" sheet
  var newSpreadsheet = SpreadsheetApp.create(RESPONSE);
  var newsheet = newSpreadsheet.getSheetByName('Sheet1');
  var copysheet = oldsheet.copyTo(newSpreadsheet);
  copysheet.getDataRange().copyTo(newsheet.getDataRange());

  var numberOfColumns = oldsheet.getLastColumn();
  for (columnNumber = 1; columnNumber <= numberOfColumns; columnNumber++){
    var Width = oldsheet.getColumnWidth(columnNumber);
    newsheet.setColumnWidth(columnNumber, Width);
  };

  newSpreadsheet.deleteSheet(copysheet);

  var newSpreadsheetID = newSpreadsheet.getId();
  var file = DriveApp.getFileById(newSpreadsheetID);
  folder.addFile(file); 
  DriveApp.removeFile(file);
  clearYellow(); //clears contents of yellow cells
  clearGray(); //clears contents of gray cells
}