1

I have been trying to get active sheet id from [this answer][1] using:

function getActiveSheetId(){
  var id  = SpreadsheetApp.getActiveSheet().getSheetId();
  Logger.log(id.toString());
  return id;
}

but my logger logs 0. Is there some other way to get the same? I want to read this sheet from another sheet file and then perform the operations.

[1]: https://stackoverflow.com/questions/26682269/get-google-sheet-by-id#:~:text=filter(%20function(s)%20%7B,Logs%20or%20use%20the%20debugger.

Shivam Sahil
  • 4,055
  • 3
  • 31
  • 62
  • 1
    When new Spreadsheet is created, the sheet ID of the 1st sheet is `0` as the default value. This is the current specification of Google side. I thought that `0` in your case might be due to this. How about this? But if my understanding of your question is not correct, I apologize. – Tanaike Aug 26 '20 at 08:26

1 Answers1

2

There is nothing wrong with the code.

It returns 0 if you apply this function to the first sheet, which is the correct sheet id as you can see from the url of the page:

example1

and if you apply the same function to a different sheet you get again the correct sheet id:

example2


If you want to get a sheet by its id then refer to this post:

Get Google Sheet by ID?

  • Example:

     function getSheetById(id) {
     return SpreadsheetApp.getActive().getSheets().filter(
      function(s) {return s.getSheetId() === id;}
    )[0];
    }
    

for example if you want to get the first sheet (id=0) then do that:

var sheet = getSheetById(0);

And then you can apply all the sheet operations to this sheet as usual.

Marios
  • 26,333
  • 8
  • 32
  • 52