8

In Google Sheets, after selecting a series of rows and right clicking on one of them, there is an option under Row Height that is Fit to Data. I would like to do this in a script.

All of my searching says no but I am hopeful. Columns are covered nicely but rows do not appear to be covered.

Thank you.

TC Lawrence
  • 133
  • 1
  • 3
  • 5
  • Check out [this answer](https://stackoverflow.com/questions/60091644/in-a-google-document-how-to-set-a-tables-multiple-rows-height-to-match-the-cell/60096817#60096817) – Aerials Feb 21 '20 at 11:46

3 Answers3

12

From what I know it isnt possible to have the rows automatically fit to data, this can only be done for columns with autoResizeColumn().

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

sheet.getRange('a1').setValue('Whenever it is a damp, drizzly November in my soul...');

// Sets the first column to a width which fits the text
sheet.autoResizeColumn(1);

However, if you know how much space your data will take you can just use a setRowHeight(). I think this is the only option you have for rows, columns seemed to be the prefered part to auto-fit.

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

// Sets the first row to a height of 200 pixels
sheet.setRowHeight(1, 200);

Hope this helps!

Taum
  • 321
  • 2
  • 19
7

This is kind of an old question but it seems that this functionality has since been added.

Now you can use the autoResizeRows() function.

The documentation explains it well.

https://developers.google.com/apps-script/reference/spreadsheet/sheet#autoResizeRows(Integer,Integer)

ggrant
  • 452
  • 7
  • 15
  • An error occurs when a value greater than 26 is given. "Exception: Those columns are out of bounds." How to fix it? – TipVisor Feb 20 '21 at 02:47
0
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

sheet.setColumnWidths(1, sheet.getMaxColumns(), 120).setRowHeights(1, sheet.getMaxRows(), 21)

120 and 21 are current defaults, I'm not sure these values are available via API

Tarasovych
  • 2,228
  • 3
  • 19
  • 51