Search code examples
google-apps-scriptgoogle-sheetsgoogle-sheets-query

dynamic data range from multiple tabs in a google sheet using QUERY function


I'm trying to create a custom function so that I can dynamically return all the tabs within a spreadsheet to use within the QUERY function.

So that in the future if I add a new tab of data, I won't need to manually update the function.

function myFunction() {
  var out = new Array();
  var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
  for (var i=0 ; i<sheets.length ; i++) {
    var name = sheets[i].getName();

    if (i !== sheets.length - 1) {

      out.push("'"+sheets[i].getName()+ "'!$A:$F; " ); 
    } else {
      out.push("'"+sheets[i].getName()+ "'!$A:$F " );
    }
  }

  return out;
}

Example of how I will use my custom function

=query(myFunction(),"select * where Col4 = 'Partner' order by Col1 desc",0)

Solution

  • function getMyDataRanges() {
      var out=[];
      var sheets=SpreadsheetApp.getActive().getSheets();
      for(var i=0;i<sheets.length;i++) {
        var sh=sheets[i];
        var name=sh.getName();
        out.push("'" + name + "'!$A:$F"); 
      }
      return '{' + out.join(';') + '}';
    }
    

    I loaded the cell with something like this;

    function loadFormula(sheetName,A1Range) {
      var ss=SpreadsheetApp().getActive();
      var sh=ss.getSheetByName(sheetName);
      var formula=Utilities.formatString('=QUERY(%s,"select * where Col4 = \'Partner\' order by Col1 desc")',getMyDataRanges());
      sh.getRange(A1Range).setFormula(formula);
    }