简体   繁体   中英

Google Apps Script - Get sheets by tab color

I am curious if there is a way to get sheets by the color of their tabs within Google Script?

I currently use this array to grab the sheets by name:

function AddRow() {
  var ss = SpreadsheetApp.openById('spreadsheetId');
  var contractorSheets,i,L,sheet;
contractorSheets = [
  "Employee 1's Timesheet",
  "Employee 2's Timesheet",
  "Employee 3's Timesheet",
  "Employee 4's Timesheet",
  "Employee 5's Timesheet",
  "Employee 6's Timesheet",
  "Employee 7's Timesheet"
]
L = contractorSheets.length;
for (i=0;i<L;i++){
  sheet = ss.getSheetByName(contractorSheets[i]);
  sheet.insertRowAfter(sheet.getLastRow());
  }
}

Timesheets are constantly being created and deleted, and I would have to update this array every time that happens. However, all the timesheet tabs are orange (#ff9900) so I figured if I could pull tabs by that color, it wouldn't matter what the name was and in the long run, make the spreadsheet a lot more dynamic regardless of turnover and sheet names.

Thank you for any help!

Try something like this

function addRow() {
SpreadsheetApp.openById('xxxxxxxxxxxxxxxyPz4').getSheets()
    .filter(function (sh) {
        return sh.getTabColor() == '#ff9900'; //change to match color
    }).forEach(function (sh) {
        sh.insertRowAfter(sh.getLastRow());
    })
}

This is easily done using already available methods:

function getSheetsWithTabColor_(colorHex, allSheets) {
  if (!allSheets || !allSheets.length)
    allSheets = SpreadsheetApp.getActive().getSheets();
  return allSheets.filter(function (sheet) { return sheet.getTabColor() === colorHex; });
}

function foo() {
  const sheets = SpreadsheetApp.getActive().getSheets();
  const timesheets = getSheetsWithTabColor_("some color hex", sheets);
  timesheets.forEach(function (sheet) {
    /** do your stuff that should be done on sheets with this color tab */
  });
}

References

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM