'How to delete empty columns with header in google sheet?

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?



Solution 1:[1]

Delete All Empty Columns

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().

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Cooper