Home > Software engineering >  getFontColorObject() not returning correct color hex on Google Apps Script
getFontColorObject() not returning correct color hex on Google Apps Script

Time:11-03

I am trying to create a function which will return the text color of a specified cell. But it never returns the correct color of the cell and instead always returns "#ff000000" no matter the text color of the cell. an example of someone useing the function is "=fontColor("A1:A1")". `

function fontColor(a) {
  var b=a;
  if(b==undefined){
    b="A1:A1";
  }
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];
  var range = sheet.getRange(b);
  
  return range.getFontColorObject().asRgbColor().asHexString();
}

`

I tried using "Logger.log" to see if the function worked and tried the function in a google sheet but both times it returned "#ff000000". I tried this on cells which had text colors of blue and ones which had text colors of black. I was expecting the function to return the correct color for example it should return "#000000" for black and "#0000ff" for blue.

CodePudding user response:

var sheet = ss.getSheets()[0];

No matter what range string you send, only the first sheet's range is returned.

=fontColor("A1")

in Sheet3 will only return the first sheet's A1's color. Try directly calling getRange() on spreadsheet:

var range = ss.getRange(b);

Then you can try:

=fontColor("Sheet3!A1")

Note that the return value as per docs is

Returns the color as a CSS-style 7 character hexadecimal string (#rrggbb) or 9 character hexadecimal string (#aarrggbb).

If 9 character #aarrggbb string is returned, the first aa is the alpha/transparency channel.

CodePudding user response:

I believe that the problem I was having has nothing to do with the code but rather with google sheets. If you never change the font color manually or just keep the font color as the default black then it will return an incorrect value, but if you change the color manual then it will return the correct value. Example: if you change the color to cyan then it will correctly return "#00ffff" and if you change the color back to black then it will correctly return "#000000", but if you never change the color and leave it at the default black then it will return "#ff000000". My best guess is that the default value of the font color of a cell is "#ff000000" and wont represent the correct color code until you manually change it.

  • Related