0
votes

I'm trying to delete all tabs if the actual tab naming doesn't exist in an array.

Sample data - May
Sample Data - April

I provide two samples to illustrate how raw data gets pulled in every month. In my code, I have API pulling process that does this job automatically every month. My below code here takes this raw data and splits them into separate tabs according to the "Vendor" column:

function SpreadProduct() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = SpreadsheetApp.getActiveSheet();
  var values = sheet.getDataRange().getValues();
  // remove header row values from array
  values.shift();

  // data structure
  var ds = {};
  values.forEach(function(row) {
    var ven = row.shift(); // 1st col
    var product = row.shift(); // 2nd col

    ds[ven] = ds[ven] || {};
    ds[ven][product] = ds[ven][product] || [];
    // set value on ds

    ds[ven][product] = [parseInt(row[0]), parseInt(row[1])];
  });
  Logger.log(ds);
  // result object, for each vendor create array of rows
  // { A: [ row, row... ]... }
  var rs = {};
  Object.keys(ds).forEach(function(v) {
    rs[v] = rs[v] || [];
    Object.keys(ds[v]).forEach(function(p) {
      if (ds[v][p]) {
        rs[v].push([p, ds[v][p][0], ds[v][p][1]]);
      } else {
        rs[v].push([p, 0, 0]);
      }
    });
  });
  Logger.log(rs);
  // write rows
  Object.keys(rs).forEach(function(v) {
    var headers = [[v, 'Product'].join(' '), 'Sales', 'leftover'];
    // insert headers into rows for writing
    rs[v].unshift(headers);
    try {
      ss.insertSheet(headers[0]);
    } catch (e) {}
    var sh = ss.getSheetByName(headers[0]);
    sh.clear();
    sh.getRange(1, 1, rs[v].length, 3).setValues(rs[v]);
  });
}

The Google Sheets tables are the results of the above code.

Now Im trying to delete the tab if the following month doesnt have previous month`s vendor.

So for instance, "Month of April" doesn`t have "Apple" in the vendor column whereas "Month of March" has "Apple".

So when I compute the table for April, the "Apple" tab was deleted

Would there be a way to do this process programmatically in Google sheet script?

1
Take a look at Spreadsheet.getSheets() it gives you an array of all of the sheets in a spreadsheet.Cooper

1 Answers

1
votes

Try this:

function delTabs() {
  var ss=SpreadsheetApp.getActive();
  var shts=ss.getSheets();
  var kA=['Sheet118','Sheet119','Sheet120','Sheet121','Sheet122','Sheet123'];
  for(var i=0;i<kA.length;i++) {
    if(kA.indexOf(shts[i].getName())==-1) {
      ss.deleteSheet(shts[i]);//if not in array
    }
  }
}