Google-sheets – Automatically add borders around nonempty cells

conditional formattinggoogle sheets

I'm looking to have cell borders automatically applied when a cell is not empty. I thought I could use conditional formatting for this, but it doesn't seem to be an option.

Best Answer

This is possible with a script ("Tools > Script editor"), using setBorder method. Here is a little demo script

function onEdit() {
  var cell = SpreadsheetApp.getActiveRange();
  if (cell.getValue() !== "") {
    cell.setBorder(true, true, true, true, true, true);
  }
  else {
    cell.setBorder(false, false, false, false, false, false);
  }
}

This runs on every edit, puts borders on the active cell/range if it's nonempty, removes them otherwise.

However, the above logic is too simple. If a cell is made blank by an edit, but has non-blank neighbors, some borders should be kept. Here is a version that addresses this by removing all borders and repainting them around non-blank cells.

function onEdit() {
  var range = SpreadsheetApp.getActiveSheet().getDataRange();
  range.setBorder(false, false, false, false, false, false);
  var values = range.getValues();
  for (var i = 0; i < values.length; i++) {
    for (var j = 0; j < values[i].length; j++) {
      if (values[i][j] !== "") {
        range.getCell(i + 1, j + 1).setBorder(true, true, true, true, true, true);
      }
    }
  }
}

But the constant flashing of all borders is annoying and slow and annoying. It's better to have this painting job invoked manually, via a menu. Here's my final version of the script: it adds a menu item "Custom > Borders for nonempty cells" whenever the spreadsheet is opened.

function onOpen() {
 var menu = [{name: "Borders for nonempty cells", functionName: "borders"}];
 SpreadsheetApp.getActiveSpreadsheet().addMenu("Custom", menu);
}

function borders() {
  var range = SpreadsheetApp.getActiveSheet().getDataRange();
  range.setBorder(false, false, false, false, false, false);
  var values = range.getValues();
  for (var i = 0; i < values.length; i++) {
    for (var j = 0; j < values[i].length; j++) {
      if (values[i][j] !== "") {
        range.getCell(i + 1, j + 1).setBorder(true, true, true, true, true, true);
      }
    }
  }
}