João Abrantes
João Abrantes

Reputation: 4883

Auto-Resize column in Google Sheet

I'm trying to resize the last column of a Google Sheet by doing:

sheet.autoResizeColumn(col);

And I get the error:

Cannot auto-resize column at column index ‘40’ because there are only ‘40’ columns. (line 165, file "Code")

The error says there are 40 columns and I am trying to change the last one, what's the problem? The counting starts at 1 in Google Script. If I do sheet.autoResizeColumn(col-1); everything works but the wrong column gets resized.

Upvotes: 1

Views: 2175

Answers (2)

OblongMedulla
OblongMedulla

Reputation: 1595

This is a way of doing it:

function onEdit()   {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0]; 
  var cell = ss.getRange("AN:AN");
      cell.setFontSize(12);
      cell.setHorizontalAlignment("center");
      for (var i = 40; i < 41; i ++){ 
sheet.autoResizeColumn(i); }  
}

Upvotes: 1

Karl
Karl

Reputation: 16

Google has broken something (edit: and since fixed it - autoResizeColumn() of last column of a sheet should no longer be returning an error message).

I have code that I've been using for several months that has now decided to not work, with the same issue. My code is longwinded and too big to paste in here, but I get "Cannot auto-resize column at column index ‘6’ because there are only ‘6’ columns. (line 648, file "Code")" even though there are clearly 6 columns and autoResizeColumn() works with column references (1-6), not array references (0-5). The code worked fine several days ago and nothing has been changed by me.

If I modify my code to reference 0-5 instead, I get an out of bounds error (there is no column 0). If I modify my code to reference 1-5 it works fine, except that column 6 doesn't get auto resized (as expected).

A work around is to add an extra blank column to the sheet while the script does it's auto-resizing and then delete that column.

Upvotes: 0

Related Questions