ssurendr
ssurendr

Reputation: 456

Any quick way to delete predefined multiple columns?

I will have a periodic spreadsheet that gets generated with a lot of information. (Some 153 columns.) But I only need to keep a fraction of those. So I planned on writing a script that will be run to delete a predefined set of columns.

Example:

Columns from initial spreadsheet:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
A B C D E F G H I J  K  L  M  N

I only want columns 2-4, 8, 10, & 13-14 to be left, say.

Columns from final spreadsheet after script is run:
1 2 3 4 5 6 7
B C D H J M N

The only way I can think of is where I carry a counter and each time I delete a column I have to adjust by 1 to accurately delete the next desired column in the loop.

Is there not a deleteColumns(2,7,12,...) type code..?

Thank you.

Upvotes: 1

Views: 917

Answers (1)

Mogsdad
Mogsdad

Reputation: 45750

Count backwards - that way the things you delete have no impact on the rest of your work.

...
var sheet = blahblahblah;
var lastCol = sheet.getLastColumn();
var keep = [2,3,4,8,10,13,14]; // array of column numbers to keep

for (var col=lastCol; col > 0; col--) {
  if (keep.indexOf(col) == -1) {
    // This isn't a keeper, delete it
    sheet.deleteColumn(col);
  }
}
...

Upvotes: 2

Related Questions