Someone asked this before but not working How do I delete empty columns with the header in google sheet? I still have issues that it shows cannot delete the column but only can hide. How to make the code work?
function deleteAllEmptyColumns() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getActiveSheet();
const cols = sh.getLastColumn();
let d = 0;
[...Array.from(new Array(cols).keys())].forEach((idx => {
if (sh.getRange(1, idx + 1 - d, sh.getLastRow()).getValues().flat().filter(e => e).length == 0) {
sh.deleteColumn(idx + 1 - d++);//delete counter increments here
}
}));
sh.deleteColumns(sh.getLastColumn() + 1, sh.getMaxColumns() - sh.getLastColumn());
}
You must remember to keep track of the columns deleted to the left of getLastColumn().