Reputation: 35
I want to define a specific sheet as an id value using the getSheetById()
function.
It is said that getSheetId()
is undefined and does not work.
The code I used is as follows.
function getSheetById(gid){
for (var sheet in SpreadsheetApp.getActiveSpreadsheet().getSheets()) {
if(sheet.getSheetId() == gid){
return sheet;
}
}
}
Upvotes: 2
Views: 1345
Reputation: 201693
I believe your goal is as follows.
When I saw your script, in the case of for (var sheet in SpreadsheetApp.getActiveSpreadsheet().getSheets()) {}
, sheet
is index. I thought that this is the reason of your issue. In this case, how about using "for...of" as follows?
function getSheetById(gid){
for (var sheet of SpreadsheetApp.getActiveSpreadsheet().getSheets()) {
if(sheet.getSheetId() == gid){
return sheet;
}
}
}
Or, I thought that in this case, find
might be able to be also used as follows.
function getSheetById(gid) {
return SpreadsheetApp.getActiveSpreadsheet().getSheets().find(s => s.getSheetId() == gid);
}
gid
is given to the function getSheetById
, the Sheet object is returned.gid
is given to the function getSheetById
, null
is returned.Upvotes: 2