且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在多个工作表(Google工作表)上运行脚本

更新时间:2023-12-05 19:17:28

您可以通过2种方法来实现.使用排除"或仅".

You can do it 2 ways. Using 'exclude' or 'only'.

排除是指,如果当前工作表是其中之一,则不要这样做.

exclude means, do not do it if current sheet is one of these.

表示仅在当前工作表是其中之一时才这样做.

only means, do it only if current sheets is one of these.

使用以下代码并启用任何一个选项,然后尝试.要启用,请将相应的工作表名称添加到 excludes only 数组中,并通过取出//取消注释行.它仅适用于当前工作表,不适用于电子表格中的所有工作表.

Use below code and enable any one option then try. To enable, add respective sheet names to excludes or only array and uncomment lines by taking out //. It'll work only on current sheet, not all sheets in the spreadsheets.

function onEdit() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var s = ss.getActiveSheet();

  // use only one of these 2 options

  // add sheets names to exclude, example ['Sheet1', 'Sheet2']
  // to exclude these sheets enable these 2 lines below by uncommenting
  // var excludes = [];
  // if (excludes.indexOf(s.getName()) != -1) return;

  // add sheet names to work on only these sheets, as above
  // to work on only these sheets enable these 2 lines below by uncommenting
  // var only = [];
  // if (only.indexOf(s.getName()) == -1) return;

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

编辑

function onEdit() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var only = [
    'Proposal',
    'Materials List - All',
    'Materials List - Shingles',
    'Materials List - Access',
    'Work Order'
  ];
  only.forEach(function(name) {
    var s = ss.getSheetByName(name);
    s.showRows(1, s.getMaxRows());
    s.getRange('B:B')
      .getValues()
      .forEach(function(r, i) {
        if (r[0] == 'Hide') s.hideRows(i + 1);
      });
  });
}