Google Sheet 查询 - 动态构建引用数组

Google Sheet Query - Building Reference Array Dynamically

我在一个文件中有多个选项卡,想将同一范围合并到一个主选项卡中。

我做了一个查询

=QUERY({source1!AR5:AU;source1!AR5:AU}, "select Col1,Col2,Col3,Col4 where Col1 is not null order by Col1", 0)

但最后我会有越来越多的标签(大约 30 个),我不想每次都手动更改我的查询。我该怎么办?

我在某处看到可以使用宏来创建函数,您知道代码吗? 我只是想在另一个选项卡中添加所有选项卡名称的地方变得简单

尝试:

function myFunction() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheets = ss.getSheets();
  var allSheets = [];
  // Append more names if you want to exclude more
  // Since 'query' is master sheet, excluded it as well
  // Remove 'query' below if you want to include it in the formula
  var excludedTabs = ['other', 'random', 'query'];
  
  sheets.forEach(function (sheet){
    var sheetName = sheet.getSheetName();
    if (!excludedTabs.includes(sheetName)){
      allSheets.push(sheetName);
    }
  });

  // Set formula in A1 cell in "query" sheet
  // Modify A1 to change the cell
  var cell = ss.getSheetByName('query').getRange("A1"); 
  cell.setFormula("=QUERY({" + allSheets.join('!AR5:AU;') + "!AR5:AU}, \"select Col1,Col2,Col3,Col4 where Col1 is not null order by Col1\", 0)");
}

这会将公式设置为 sheet queryA1,请随时通过更改 A1 和 [=12= 来更改设置公式的位置].

您还可以添加 sheet 要排除的内容。将其附加到 excludedTabs 数组。

示例输出:

已添加示例 sheet 以检查新的 sheet 个案例。

添加了预期的公式。 (不包括 queryrandomother sheets)