最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Cannot find method setActiveSheet(string) - Stack Overflow

matteradmin8PV0评论

In Google Sheets, which runs on JavaScript, I'm getting this message, "Cannot find method setActiveSheet(string). (line 4, file "Code")", I don't know why... I'm pretty new to coding, so bear with me.

function onOpen() {
  var email = Session.getActiveUser().getEmail();
  var sheet = email.slice(0,-11);
  SpreadsheetApp.setActiveSheet(sheet)
}

In Google Sheets, which runs on JavaScript, I'm getting this message, "Cannot find method setActiveSheet(string). (line 4, file "Code")", I don't know why... I'm pretty new to coding, so bear with me.

function onOpen() {
  var email = Session.getActiveUser().getEmail();
  var sheet = email.slice(0,-11);
  SpreadsheetApp.setActiveSheet(sheet)
}
Share Improve this question asked Feb 1, 2015 at 2:17 NonCreature0714NonCreature0714 6,03410 gold badges33 silver badges55 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

You're getting the "Cannot find method" error because the setActiveSheet() method takes an argument of type Sheet, not a string. See the specification here: https://developers.google./apps-script/reference/spreadsheet/spreadsheet-app#setActiveSheet(Sheet)

In order to get a Sheet object from the string, you need to open the parent Spreadsheet, then get the appropriate sheet by name, then you can pass it to setActiveSheet.

Assuming this script is embedded in the relevant Spreadsheet, that looks like this:

var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
SpreadsheetApp.setActiveSheet(spreadsheet.getSheetByName(sheet));

This worked well for me.

function theSecondSheet() {
   var activeSpreadSheet = SpreadsheetApp.getActiveSpreadsheet();
    if(activeSpreadSheet.getSheetByName("Sheet2").activate()){
     SpreadsheetApp.setActiveSheet(activeSpreadSheet.getSheetByName("Sheet2"));
    }
}
Post a comment

comment list (0)

  1. No comments so far