It's my first time working with Google scripts. I want to change the background color of a row and text when the row contains certain values. I've had some success using this piece of code:
function onEdit()
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Sheet1');
var rows = sheet.getRange('a1:z');
var numRows = rows.getNumRows();
var values = rows.getValues();
for (var i = 0; i <= numRows - 1; i++)
{
var n = i+1;
var backgroundColor;
var textColor;
if(values[i].indexOf('Won'))
{
backgroundColor = 'red';
textColor = 'blue';
}
else if(values[i].indexOf('Lost'))
{
backgroundColor = 'green';
textColor = 'yellow';
}
sheet.getRange('a'+n+':z'+n).setBackgroundColor(backgroundColor);
sheet.getRange('a'+n+':z'+n).setFontColor(textColor);
}
}
So now rows containing Won turn green with yellow text, and rows containing Lost turn red with blue text.
A couple of problems:
- Every empty row also turn red- how do I fix this?
- My if/else function seems to be inverted, yet it works perfectly. The way I understand it is that if the row contains Won it should actually turn red with blue text. Can anyone help me understand this part better?