Sandeep S D
Sandeep S D

Reputation: 647

getID from named sheet

Is there a way to get the ID (string) from a named sheet? I am trying to apply a filter to a named sheet. All the examples I have seen is to get the id from the active sheet. But I want to use it for a named sheet. How do I do it?

var resultSheet = spreadsheetApp.getActiveSpreadsheet().getSheetByName("Result");
Sheets.Spreadsheets.batchUpdate({'requests': request}, resultSheet.getSheetId());

Upvotes: 1

Views: 6556

Answers (3)

Sandeep S D
Sandeep S D

Reputation: 647

Thanks to the post, I got the answer I was looking for. Here is the code that I can use.

var resultSheet = spreadsheetApp.getActiveSpreadsheet().getSheetByName("Result");
var myID = resultSheet.getParent().getID();
Sheets.Spreadsheets.batchUpdate({'requests': request}, myID);

This will help me to avoid sheet switching.

Upvotes: 0

tehhowch
tehhowch

Reputation: 9872

There are two relevant "ID" types for Google Sheets - one corresponds to the currently-open Google Sheets file - the spreadsheetId which is also the exact same value as the Google Drive fileId - and the other corresponds to a specific Sheet within the Google Sheets spreadsheet, and is interchangeably known as a gridId or sheetId.

From a given Sheet object, you can use the class method getParent() to obtain a reference to the enclosing Spreadsheet object. A Spreadsheet has the method getId() which will return the needed fileId/spreadsheetId for the Sheets API batchUpdate method.

It is very common to already have a reference to the spreadsheet:

const wkbk = SpreadsheetApp.getActive();
const sheet = wkbk.getSheetByName("some name");
// ...
Sheets.Spreadsheets.batchUpdate({'requests': request}, wkbk.getId());

Depending on how your code is structured this reference may be out of scope, and perhaps you don't want to / can't include the relevant ID in the function's argument list:

function foo() {
  const wkbk = SpreadsheetApp.getActive();
  const wkbkId = wkbk.getId();
  // ...
  doSheetUpdate_(wkbk.getSheetByName("some name"));
  // ...
}
function doSheetUpdate_(sheet) {
  const wkbkId = sheet.getParent().getId();
  const rq = getRequest_(sheet.getSheetId());
  // ...
  const resp = Sheets.Spreadsheets.batchUpdate({'requests': rq}, wkbkId);
}
function getRequest_(sheetId) {
  // ...
}

Upvotes: 1

Swordstoo
Swordstoo

Reputation: 885

Use: var sheetID = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Your sheet name").getSheetId();

sheetID will contain a string with the sheet's ID

See the documentation here: https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet#getsheetid

Upvotes: 0

Related Questions