Search code examples
google-apps-scriptgoogle-sheetsautosize

Combining autoResizeRows and setting empty rows to a size of 1


My goal is to set empty rows to a hight of 1 and filled ones to a fitting size (autosized) but I cant find a way to combine those two.
This is, what I'm currently using but it sets empty rows to 21 instead of 1:

function Higth() { 
var s = SpreadsheetApp.getActive().getActiveSheet();

s.autoResizeRows(5, 31);
// 5 is the row in which the resizing starts and 31 is the amount of rows this is done
}

I hope someone knows a way to do this.

Jonah


Solution

  • I suggest you use the implementation in this SO post, given the active range:

    function changeRowHeight()
    {
      var ss=SpreadsheetApp.getActiveSpreadsheet();
      var sht=ss.getActiveSheet()
      var rng=sht.getActiveRange();
      var row=rng.getRow();
      var numrows=rng.getNumRows();
      var resp=SpreadsheetApp.getUi().prompt('Get Row Height', 'Enter Row Height in Pixels', SpreadsheetApp.getUi().ButtonSet.OK);
      var height = Number(resp.getResponseText());
      for(var i=0;i<numrows;i++)
      {
        sht.setRowHeight(row + i, height)
      }
    }
    

    Then you can insert some if() statement to check if the given row is filled with text using the autoResizeRowsfunction given in the Apps Script documentation. It should be something like this:

    Sets the height of all rows starting at the given row position to fit their contents.

    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = ss.getSheets()[0];
    
    // Sets the first 15 rows to a height that fits their text.
    sheet.autoResizeRows(1, 15);