Google-sheets – Changing the fontColor of cells when editing

google sheetsgoogle-apps-script

I'm trying to write an Apps Script that change the font color of a cell when it value changes.

I found a way to to change de fontColor of a range, and add to trigger 'onEdit', but the all range is changing and not the single cells that I've been modify.

Here is my Script :

function changeFontColor() {
  
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheetA1 = ss.getSheetByName('Voltaire');
  var lastRow = sheetA1.getLastRow();
  var lastColumn = sheetA1.getLastColumn();
  var dataRange = sheetA1.getRange(3, 3, lastRow -6, lastColumn);

  
  dataRange.setFontColor('Red');

} 

Best Answer

Using the edit event object.

function changeFontColor(e) {

   e.range.setFontColor('Red');

}
  • On the first line e is used to "catch" the edit event object.
  • On the "last statement" e.range is used instead of dataRange.
  • All other statements aren't required.

Using getActiveRange (no edit event object)

function changeFontColor() {
  
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  ss.getActiveRange().setFontColor('Red');

}
  • On the "last statement" ss.getActiveRange() is used instead of dataRange.
  • Only the first and the last statements are required.

Related