I am trying to use .getSheetByName('') to grab a sheet whose name contain a certain string like, 'V1' or 'V4', not an exact match. Say the name of the sheet is '2020 0304 V1', the first part is always changing but it contains V1, I tried .getSheetByName('*V1') but it is not working. Any hint on how to achieve this?
Unfortunately, in the current stage, the method like the regex cannot be used with getSheetByName()
. So in this case, it is required to use the workarounds.
In this answer, I would like to propose 2 patterns.
In this pattern, test
is used for searching the sheet name. getSheetName()
is used for retrieving the sheet name. In this case, it supposes that the pattern is like 2020 0304 V1
.
function myFunction() {
const searchText = "V1";
const sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
const regex = RegExp(`\\d{4} \\d{4} ${searchText}`);
const sheet = sheets.filter(s => regex.test(s.getSheetName()));
if (sheet.length > 0) console.log(sheet[0].getSheetName());
}
\d{4} \d{4} V1
in your Spreadsheet, you can retrieve the sheet by sheet[0]
.In this pattern, includes
is used for searching the sheet name. getSheetName()
is used for retrieving the sheet name.
function myFunction() {
const searchText = "V1";
const sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
const sheet = sheets.filter(s => s.getSheetName().includes(searchText));
if (sheet.length > 0) console.log(sheet[0].getSheetName());
}
V1
in your Spreadsheet, you can retrieve the sheet by sheet[0]
.