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 doesn
t 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?
Spreadsheet.getSheets()
it gives you an array of all of the sheets in a spreadsheet. – Cooper