duplicateActiveSheet() not working with getSheetByName()

时间:2015-05-04 19:43:40

标签: google-apps-script google-sheets

I could easily being doing something wrong but when using a blank sheet and Google App Script to duplicate the active sheet obtained with getSheetByName(), I get a TypeError.

function myFunction() {
  var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
  if (ss !== null) {
    Logger.log(ss.getName()); // log: Sheet1
    Logger.log(ss.getSheetName()); // log: Sheet1
    Logger.log(SpreadsheetApp.getActiveSheet().getSheetName()); // log: Sheet1
    ss.duplicateActiveSheet(); // TypeError: Cannot find function duplicateActiveSheet in object Sheet.
  }
}

1 个答案:

答案 0 :(得分:1)

方法duplicateActiveSheet()spreadsheet method,而不是工作表方法。

修改您的代码,如下所示:

function myFunction() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sh = ss.getSheetByName('Sheet1');
  if (sh !== null) {
    sh.activate();// make this sheet active
    Logger.log(sh.getName()); // log: Sheet1
    ss.duplicateActiveSheet();
  }
}

您可以使用脚本编辑器中的自动完成功能轻松避免此类错误。

只需在变量后键入一个句点(。),您就可以使用"控制空间"来查看所有可用的方法。在你的键盘上。

enter image description here