Google Sheets – How to Create Dynamic Borders for Columns

google sheetsgoogle-apps-script

I have this script that sets borders for range if first cell is not empty

function borders() {

   var ss = SpreadsheetApp.getActiveSpreadsheet();
   var sheetmon = ss.getActiveSheet()
  var rows = sheetmon.getRange('A55:AY177'); 
  var numRows = rows.getNumRows(); 
  var values = rows.getValues(); 
  var testvalues = sheetmon.getRange('A55:A177')

  rows.setBorder(false, false, false, false, false, false, "black", SpreadsheetApp.BorderStyle.SOLID_MEDIUM); 

  for (var i = 0; i <= numRows - 1; i++) {
      var n = i + 55;
      Logger.log(testvalues[i] > 0);
      if (testvalues[i] == '') { 
      } else {
        Logger.log(testvalues[i]);
        sheetmon.getRange('A' + n + ':AY' + n).setBorder(true, true, true, true, true, true, "gray", SpreadsheetApp.BorderStyle.SOLID); 
     }
  }}

Question – how to set dynamic final column for setBorder? Instead of column AY I want to set the one where the last cell in row 53 is not empty.

Best Answer

To get the last cell in a row that isn't empty, try this based on a JavaScript trick that I found on an answer to Determining the last row in a single column

var values = SpreadsheetApp.getActiveSheet().getRange("53:53").getValues();
var last = values[0].filter(String).length;

The above assumes that all the row cells are continuos (no blank cells between two non-blank cells).