Search code examples
google-apps-scriptgoogle-sheetsgoogle-appsgoogle-sheets-macros

Trying to loop setFormula() through open sheets


I'm using an add-on (toTabs) that separates a sheet of data based on the value in column H. It generates a new sheet for each unique value in H2:H, and then places a filter() in cell A2 on each sheet. This works wonderfully, except my next step is to export each sheet to .csv, and I need to get rid of H:H before doing that.

I'm trying to write a script that changes each filter from A2:H to A2:G and either ignores the rest of the formula, or replaces the text that the filter searches for to the sheet name, then loops through every sheet except for specific sheets. I feel like I'm 95% of the way there, but the loop isn't working quite right. Here's what I have so far:

function Loop() {
  var ss = SpreadsheetApp.getActive();
  var allsheets = ss.getSheets();

  // Array holding the names of the sheets to exclude from the execution
  var exclude = ["Raw Input","Remove Chuff","Filtered Input","Final Input","Data Values","blank","totabs"];

  for(var s in allsheets){
    var sheet = allsheets[s];

    // Stop iteration execution if the condition is meet.
    if(exclude.indexOf(sheet.getName())==-1) continue;

  var cell = s.getRange("A2");
  cell.setFormula('=Filter(\'Data Values\'!A2:G,\'Data Values\'!H2:H="'+ SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName() + '")');
  s.getRange('H:H').activate();
  s.getActiveRangeList().clear({contentsOnly: true, skipFilteredRows: true});
  s.getRange('F:F').activate();
  s.getActiveRangeList().setNumberFormat('00000');

  }
} 

Here's a copy of the file with all the irrelevant tabs hidden. Any help would be welcome.


Solution

  • Try this:

    function Loop() {
      var ss=SpreadsheetApp.getActive();
      var allsheets = ss.getSheets();
      var exclude = ["Raw Input","Remove Chuff","Filtered Input","Final Input","Data Values","blank","totabs"];
      for(var i=0;i<allsheets.length;i++){
        var sheet = allsheets[i];
        if(exclude.indexOf(sheet.getName())!=-1) continue;
        sheet.getRange("A2").setFormula('=Filter(\'Data Values\'!A2:G,\'Data Values\'!H2:H="'+ sheet.getName() + '")');
        sheet.getRange(1,8,sheet.getLastRow(),1).clear({contentsOnly: true, skipFilteredRows: true});
        sheet.getRange(1,6,sheet.getLastRow(),1).setNumberFormat('00000');
      }
    }