Search code examples
google-sheetsgoogle-sheets-macros

How to use Google app script to automatically border line below When Value Changes


I want to add a border line below the row whenever column C value changes.

I haven’t touched macro for a long time, this is a script I put together but it doesn’t work as expected. Anyone know where the problem is? Thanks!

function underline() {
  var spreadsheet = SpreadsheetApp.getActive();
  var sheet = spreadsheet.getActiveSheet();
  for (var i = 1; i < 10; i++) {
    if (sheet.getRange(spreadsheet.getCurrentCell().getRow() + i, 3) != sheet.getRange(spreadsheet.getCurrentCell().getRow() + i+1, 3)) {
        sheet.getRange(spreadsheet.getCurrentCell().getRow() + i, 1, 1, sheet.getMaxColumns()).activate();
        spreadsheet.getActiveRangeList().setBorder(null, null, true, null, null, null, '#000000', SpreadsheetApp.BorderStyle.SOLID);
         }
  }

};

Solution

  • Your original code is a bit convoluted, doing a lot with a single if statement. I took the liberty to separate the complicated bit into a distinct function, findOriginal(cell). The following code adds one line:

    function findOriginal(cell) { //offsets given cell until finds new content
      while (cell.getValue() == cell.offset(1,0).getValue()) cell = cell.offset(1,0);
      return cell;
    }
    
    function underline() {
      var spreadsheet = SpreadsheetApp.getActive(),
          cell = spreadsheet.getSelection().getCurrentCell();
    
      cell = findOriginal(cell);
    
      var sheet = spreadsheet.getActiveSheet();
      sheet.getRange(cell.getRow(), 1, 1, sheet.getLastColumn()) // setting the range to border
      .setBorder(null, null, true, null, null, null, 
                 '#000000', SpreadsheetApp.BorderStyle.SOLID); // you wrote this line
    };