简体   繁体   中英

how do you apply code to all tabs on a google sheet

Novice at the google scripting ... so apologies ..

I have the below code that works ... however I have a further ten tabs that this needs to apply to ... is there a way of writing this so you don't have to reference each active sheet?

the idea is to hide rows and columns automatically if a certain value exists in them ...

function onOpen()
{
  var s = SpreadsheetApp.getActive().getSheetByName('O4');
  s.showRows(1, s.getMaxRows());

  s.getRange('BQ:BQ')
    .getValues()
    .forEach( function (r, i) {
    if (r[0] == 'Done') 
      s.hideRows(i + 1);
    });

  var b = SpreadsheetApp.getActive().getSheetByName('O4');
b.showColumns(1, b.getMaxColumns());
b.getRange('135:135')
    .getValues()[0]
    .forEach(function (r, i) {
        if (r && r == 'N') b.hideColumns(i + 1)
    });

    var s = SpreadsheetApp.getActive().getSheetByName('OG3');
  s.showRows(1, s.getMaxRows());

  s.getRange('BQ:BQ')
    .getValues()
    .forEach( function (r, i) {
    if (r[0] == 'Done') 
      s.hideRows(i + 1);
    });

  var b = SpreadsheetApp.getActive().getSheetByName('OG3');
b.showColumns(1, b.getMaxColumns());
b.getRange('135:135')
    .getValues()[0]
    .forEach(function (r, i) {
        if (r && r == 'N') b.hideColumns(i + 1)
    });
}

You can just loop over all of the tabs in your sheet using this snippet.

var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
sheets.forEach(function (sheet) {
  callYourFunction(sheet)
})

If you need to on apply your code on particular sheets do this.

var sheets = ['SheetA', 'SheetB', 'SheetG', 'SheetH', 'SheetM']
for (var i = 0; i < sheets.length; i++) {
  var sheetName = sheets[i]
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
  if (sheet != null) {
    callYourFunction(sheet)
  }
}

Hope that helps

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-2024 STACKOOM.COM