In OfficeScript, how can I make it return the number of cells with a red background?

21 Views Asked by At

I developed the script, but it always returns a value of 0, why?

I'm looking for the cells that have a red background and adding them all together and returning the total amount located.

function main(workbook: ExcelScript.Workbook) {     
  let selectedSheet = workbook.getActiveWorksheet();        
  const targetColor = "#FF0000";      
  let foundCellCount = 0;      
  let columnARange = selectedSheet.getRange("A:A");      
  let cellValues = columnARange.getValues(); 
  
  if (cellValues !== null) {       
    cellValues.forEach((row, index) => {          
      let cellBackgroundColor = columnARange.getCell(index, 0).getFormat().getFill();          
      if (cellBackgroundColor !== null) {           
        foundCellCount++;
      }
    });
  }          
  console.log(`Total is ${targetColor}: ${foundCellCount}`);
}
1

There are 1 best solutions below

0
taller On BEST ANSWER
  • Use .getColor() to get the value of filling color
  • The if cluase should be if (cellBackgroundColor === targetColor)
  • Use getUsedRange().getColumn(0) to get the used cells on Col A
  • if (cellValues !== null) can be simplified as if (cellValues)
function main(workbook: ExcelScript.Workbook) {
    let selectedSheet = workbook.getActiveWorksheet();
    const targetColor = "#FF0000";
    let foundCellCount = 0;
    let columnARange = selectedSheet.getUsedRange().getColumn(0);
    let cellValues = columnARange.getValues();
    if (cellValues) {
        cellValues.forEach((row, index) => {
            let cellBackgroundColor = 
            columnARange.getCell(index, 0).getFormat().getFill().getColor();
            if (cellBackgroundColor === targetColor) {
                foundCellCount++;
            }
        });
    }
    console.log(`Total is ${targetColor}: ${foundCellCount}`);
}