Question

The easier way might be through conditional formatting, that allows only text or background color. How do I style a min/max value of a cell in a column bold?

I want to find the cell with the smallest/biggest value in a range(A2:A) and setFontWeight('bold'). Should be one line of code. It isn't though.

It seems nobody out there has cracked that nut?! At least I can find anything helpful.

Was it helpful?

Solution

I'm quite sure there are better solutions but I got this one working for me:

function myFunction() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var data = sheet.getRange(2, 1, sheet.getLastRow() - 1)
    .getValues()
    .map(function(d){ return d[0]; });

  var min_value = Math.min.apply(null, data);

  var idx = data.indexOf(min_value);
  while(idx > -1) {
    sheet.getRange(idx + 2, 1).setFontWeight('bold');
    idx = data.indexOf(min_value, idx + 1);
  }
}

Same applies to Math.max.apply or other searches. Sadly this solution isn't quite fast especially when it comes to handle more data. I've tested it with 22 rows of random numbers and it was acceptable.

OTHER TIPS

I wrote this quick. Its not perfect but it will apply bold to the max value of a given range.

function onOpen(){
  var workbook = SpreadsheetApp.getActiveSpreadsheet();
  //Declare and set menu entry names/values
  var menuEntries = [ 
    {name: "Apply Format", functionName: "setFormatConditions"}];
  workbook.addMenu("Custom Functions", menuEntries);
}

function setFormatConditions(){
  var workbook = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = workbook.getActiveSheet();
  var aRange = "C3:C";
  var currentRange = workbook.getRange(aRange);
  var values = currentRange.getValues(); 
  var rangeColumn = currentRange.getColumn();
  var rangeRow = currentRange.getRow();
  var max = 0;

  for (var x=0;x <= values.length; x++) 

  {
    if (parseInt(values[x]) > max)
    {
     max = values[x];
     currentRange.setFontWeight('normal') 
     sheet.getRange(rangeRow + x,rangeColumn).setFontWeight('bold');
    }

  }

}

Hope it helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top